blob: 50e9f24cc18f50c43ef3122aa624c53a80a6bd5b [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"
Chris Lattner9dbb4292009-11-09 23:28:39 +000045#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000046#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000047#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000048#include "llvm/Target/TargetData.h"
49#include "llvm/Transforms/Utils/BasicBlockUtils.h"
50#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000051#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000052#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000053#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000055#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000056#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000057#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000058#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000059#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000060#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000061#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000062#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000063#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000064#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000065#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000066#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000067#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000068#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000069using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000070using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000071
Chris Lattner0e5f4992006-12-19 21:40:18 +000072STATISTIC(NumCombined , "Number of insts combined");
73STATISTIC(NumConstProp, "Number of constant folds");
74STATISTIC(NumDeadInst , "Number of dead inst eliminated");
75STATISTIC(NumDeadStore, "Number of dead stores eliminated");
76STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000077
Chris Lattnerb109b5c2009-12-21 06:03:05 +000078/// SelectPatternFlavor - We can match a variety of different patterns for
79/// select operations.
80enum SelectPatternFlavor {
81 SPF_UNKNOWN = 0,
82 SPF_SMIN, SPF_UMIN,
83 SPF_SMAX, SPF_UMAX
84 //SPF_ABS - TODO.
85};
86
Chris Lattner0e5f4992006-12-19 21:40:18 +000087namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000088 /// InstCombineWorklist - This is the worklist management logic for
89 /// InstCombine.
90 class InstCombineWorklist {
91 SmallVector<Instruction*, 256> Worklist;
92 DenseMap<Instruction*, unsigned> WorklistMap;
93
94 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
95 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
96 public:
97 InstCombineWorklist() {}
98
99 bool isEmpty() const { return Worklist.empty(); }
100
101 /// Add - Add the specified instruction to the worklist if it isn't already
102 /// in it.
103 void Add(Instruction *I) {
Jeffrey Yasskin43069632009-10-08 00:12:24 +0000104 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
105 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +0000106 Worklist.push_back(I);
Jeffrey Yasskin43069632009-10-08 00:12:24 +0000107 }
Chris Lattner873ff012009-08-30 05:55:36 +0000108 }
109
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000110 void AddValue(Value *V) {
111 if (Instruction *I = dyn_cast<Instruction>(V))
112 Add(I);
113 }
114
Chris Lattner67f7d542009-10-12 03:58:40 +0000115 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
116 /// which should only be done when the worklist is empty and when the group
117 /// has no duplicates.
118 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
119 assert(Worklist.empty() && "Worklist must be empty to add initial group");
120 Worklist.reserve(NumEntries+16);
121 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
122 for (; NumEntries; --NumEntries) {
123 Instruction *I = List[NumEntries-1];
124 WorklistMap.insert(std::make_pair(I, Worklist.size()));
125 Worklist.push_back(I);
126 }
127 }
128
Chris Lattner7a1e9242009-08-30 06:13:40 +0000129 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000130 void Remove(Instruction *I) {
131 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
132 if (It == WorklistMap.end()) return; // Not in worklist.
133
134 // Don't bother moving everything down, just null out the slot.
135 Worklist[It->second] = 0;
136
137 WorklistMap.erase(It);
138 }
139
140 Instruction *RemoveOne() {
141 Instruction *I = Worklist.back();
142 Worklist.pop_back();
143 WorklistMap.erase(I);
144 return I;
145 }
146
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000147 /// AddUsersToWorkList - When an instruction is simplified, add all users of
148 /// the instruction to the work lists because they might get more simplified
149 /// now.
150 ///
151 void AddUsersToWorkList(Instruction &I) {
152 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
153 UI != UE; ++UI)
154 Add(cast<Instruction>(*UI));
155 }
156
Chris Lattner873ff012009-08-30 05:55:36 +0000157
158 /// Zap - check that the worklist is empty and nuke the backing store for
159 /// the map if it is large.
160 void Zap() {
161 assert(WorklistMap.empty() && "Worklist empty, but map not?");
162
163 // Do an explicit clear, this shrinks the map if needed.
164 WorklistMap.clear();
165 }
166 };
167} // end anonymous namespace.
168
169
170namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000171 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
172 /// just like the normal insertion helper, but also adds any new instructions
173 /// to the instcombine worklist.
174 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
175 InstCombineWorklist &Worklist;
176 public:
177 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
178
179 void InsertHelper(Instruction *I, const Twine &Name,
180 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
181 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
182 Worklist.Add(I);
183 }
184 };
185} // end anonymous namespace
186
187
188namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000189 class InstCombiner : public FunctionPass,
190 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000191 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000192 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000193 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000194 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000195 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000196 InstCombineWorklist Worklist;
197
Chris Lattner74381062009-08-30 07:44:24 +0000198 /// Builder - This is an IRBuilder that automatically inserts new
199 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000200 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000201 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000202
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000203 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000204 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000205
Owen Andersone922c022009-07-22 00:24:57 +0000206 LLVMContext *Context;
207 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000208
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000209 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000210 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000211
212 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000213
Chris Lattner97e52e42002-04-28 21:27:06 +0000214 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000215 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000216 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000217 }
218
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000219 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000220
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000221 // Visitation implementation - Implement instruction combining for different
222 // instruction types. The semantics are as follows:
223 // Return Value:
224 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000225 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000226 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000227 //
Chris Lattner7e708292002-06-25 16:13:24 +0000228 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000229 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000230 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000231 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000232 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000233 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000234 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000235 Instruction *visitURem(BinaryOperator &I);
236 Instruction *visitSRem(BinaryOperator &I);
237 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000238 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000239 Instruction *commonRemTransforms(BinaryOperator &I);
240 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000241 Instruction *commonDivTransforms(BinaryOperator &I);
242 Instruction *commonIDivTransforms(BinaryOperator &I);
243 Instruction *visitUDiv(BinaryOperator &I);
244 Instruction *visitSDiv(BinaryOperator &I);
245 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000246 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000247 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000248 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000249 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000250 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000251 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000252 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000253 Instruction *visitOr (BinaryOperator &I);
254 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000255 Instruction *visitShl(BinaryOperator &I);
256 Instruction *visitAShr(BinaryOperator &I);
257 Instruction *visitLShr(BinaryOperator &I);
258 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000259 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
260 Constant *RHSC);
Chris Lattner1f12e442010-01-02 08:12:04 +0000261 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
262 GlobalVariable *GV, CmpInst &ICI);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000263 Instruction *visitFCmpInst(FCmpInst &I);
264 Instruction *visitICmpInst(ICmpInst &I);
265 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000266 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
267 Instruction *LHS,
268 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000269 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
270 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000271 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000272 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000273 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000274 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000275 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000276 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000277 Instruction *commonCastTransforms(CastInst &CI);
278 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000279 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000280 Instruction *visitTrunc(TruncInst &CI);
281 Instruction *visitZExt(ZExtInst &CI);
282 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000283 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000284 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000285 Instruction *visitFPToUI(FPToUIInst &FI);
286 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000287 Instruction *visitUIToFP(CastInst &CI);
288 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000289 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000290 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000291 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000292 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
293 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000294 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000295 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
296 Value *A, Value *B, Instruction &Outer,
297 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000298 Instruction *visitSelectInst(SelectInst &SI);
299 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000300 Instruction *visitCallInst(CallInst &CI);
301 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000302
303 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000304 Instruction *visitPHINode(PHINode &PN);
305 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000306 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000307 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000308 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000309 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000310 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000311 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000312 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000313 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000314 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000315 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000316
317 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000318 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000319
Chris Lattner9fe38862003-06-19 17:00:31 +0000320 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000321 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000322 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000323 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000324 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
325 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000326 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000327 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
328
Chris Lattner9fe38862003-06-19 17:00:31 +0000329
Chris Lattner28977af2004-04-05 01:30:19 +0000330 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000331 // InsertNewInstBefore - insert an instruction New before instruction Old
332 // in the program. Add the new instruction to the worklist.
333 //
Chris Lattner955f3312004-09-28 21:48:02 +0000334 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000335 assert(New && New->getParent() == 0 &&
336 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000337 BasicBlock *BB = Old.getParent();
338 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000339 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000340 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000341 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000342
Chris Lattner8b170942002-08-09 23:47:40 +0000343 // ReplaceInstUsesWith - This method is to be used when an instruction is
344 // found to be dead, replacable with another preexisting expression. Here
345 // we add all uses of I to the worklist, replace all uses of I with the new
346 // value, then return I, so that the inst combiner will know that I was
347 // modified.
348 //
349 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000350 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000351
352 // If we are replacing the instruction with itself, this must be in a
353 // segment of unreachable code, so just clobber the instruction.
354 if (&I == V)
355 V = UndefValue::get(I.getType());
356
357 I.replaceAllUsesWith(V);
358 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000359 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000360
361 // EraseInstFromFunction - When dealing with an instruction that has side
362 // effects or produces a void value, we can't rely on DCE to delete the
363 // instruction. Instead, visit methods should return the value returned by
364 // this function.
365 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000366 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000367
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000368 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000369 // Make sure that we reprocess all operands now that we reduced their
370 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000371 if (I.getNumOperands() < 8) {
372 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
373 if (Instruction *Op = dyn_cast<Instruction>(*i))
374 Worklist.Add(Op);
375 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000376 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000377 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000378 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000379 return 0; // Don't do anything with FI
380 }
Chris Lattner173234a2008-06-02 01:18:21 +0000381
382 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
383 APInt &KnownOne, unsigned Depth = 0) const {
384 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
385 }
386
387 bool MaskedValueIsZero(Value *V, const APInt &Mask,
388 unsigned Depth = 0) const {
389 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
390 }
391 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
392 return llvm::ComputeNumSignBits(Op, TD, Depth);
393 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000394
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000395 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000396
Reid Spencere4d87aa2006-12-23 06:05:41 +0000397 /// SimplifyCommutative - This performs a few simplifications for
398 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000399 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000400
Chris Lattner886ab6c2009-01-31 08:15:18 +0000401 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
402 /// based on the demanded bits.
403 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
404 APInt& KnownZero, APInt& KnownOne,
405 unsigned Depth);
406 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000407 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000408 unsigned Depth=0);
409
410 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
411 /// SimplifyDemandedBits knows about. See if the instruction has any
412 /// properties that allow us to simplify its operands.
413 bool SimplifyDemandedInstructionBits(Instruction &Inst);
414
Evan Cheng388df622009-02-03 10:05:09 +0000415 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
416 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000417
Chris Lattner5d1704d2009-09-27 19:57:57 +0000418 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
419 // which has a PHI node as operand #0, see if we can fold the instruction
420 // into the PHI (which is only possible if all operands to the PHI are
421 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000422 //
423 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
424 // that would normally be unprofitable because they strongly encourage jump
425 // threading.
426 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000427
Chris Lattnerbac32862004-11-14 19:13:23 +0000428 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
429 // operator and they all are only used by the PHI, PHI together their
430 // inputs, and do the operation once, to the result of the PHI.
431 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000432 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000433 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000434 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000435
Chris Lattner7da52b22006-11-01 04:51:18 +0000436
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000437 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
438 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000439
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000440 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000441 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000442 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000443 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000444 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000445 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000446 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000447 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000448 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000449
Chris Lattnerafe91a52006-06-15 19:07:26 +0000450
Reid Spencerc55b2432006-12-13 18:21:21 +0000451 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000452
Dan Gohman6de29f82009-06-15 22:12:54 +0000453 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000454 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000455 unsigned GetOrEnforceKnownAlignment(Value *V,
456 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000457
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000458 };
Chris Lattner873ff012009-08-30 05:55:36 +0000459} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000460
Dan Gohman844731a2008-05-13 00:00:25 +0000461char InstCombiner::ID = 0;
462static RegisterPass<InstCombiner>
463X("instcombine", "Combine redundant instructions");
464
Chris Lattner4f98c562003-03-10 21:43:22 +0000465// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000466// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000467static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000468 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000469 if (BinaryOperator::isNeg(V) ||
470 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000471 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000472 return 3;
473 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000474 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000475 if (isa<Argument>(V)) return 3;
476 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000477}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000478
Chris Lattnerc8802d22003-03-11 00:12:48 +0000479// isOnlyUse - Return true if this instruction will be deleted if we stop using
480// it.
481static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000482 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000483}
484
Chris Lattner4cb170c2004-02-23 06:38:22 +0000485// getPromotedType - Return the specified type promoted as it would be to pass
486// though a va_arg area...
487static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000488 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
489 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000490 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000491 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000492 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000493}
494
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000495/// ShouldChangeType - Return true if it is desirable to convert a computation
496/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
497/// type for example, or from a smaller to a larger illegal type.
498static bool ShouldChangeType(const Type *From, const Type *To,
499 const TargetData *TD) {
500 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
501
502 // If we don't have TD, we don't know if the source/dest are legal.
503 if (!TD) return false;
504
505 unsigned FromWidth = From->getPrimitiveSizeInBits();
506 unsigned ToWidth = To->getPrimitiveSizeInBits();
507 bool FromLegal = TD->isLegalInteger(FromWidth);
508 bool ToLegal = TD->isLegalInteger(ToWidth);
509
510 // If this is a legal integer from type, and the result would be an illegal
511 // type, don't do the transformation.
512 if (FromLegal && !ToLegal)
513 return false;
514
515 // Otherwise, if both are illegal, do not increase the size of the result. We
516 // do allow things like i160 -> i64, but not i64 -> i160.
517 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
518 return false;
519
520 return true;
521}
522
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000523/// getBitCastOperand - If the specified operand is a CastInst, a constant
524/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
525/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000526static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000527 if (Operator *O = dyn_cast<Operator>(V)) {
528 if (O->getOpcode() == Instruction::BitCast)
529 return O->getOperand(0);
530 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
531 if (GEP->hasAllZeroIndices())
532 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000533 }
Chris Lattnereed48272005-09-13 00:40:14 +0000534 return 0;
535}
536
Reid Spencer3da59db2006-11-27 01:05:10 +0000537/// This function is a wrapper around CastInst::isEliminableCastPair. It
538/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000539static Instruction::CastOps
540isEliminableCastPair(
541 const CastInst *CI, ///< The first cast instruction
542 unsigned opcode, ///< The opcode of the second cast instruction
543 const Type *DstTy, ///< The target type for the second cast instruction
544 TargetData *TD ///< The target data for pointer size
545) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000546
Reid Spencer3da59db2006-11-27 01:05:10 +0000547 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
548 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000549
Reid Spencer3da59db2006-11-27 01:05:10 +0000550 // Get the opcodes of the two Cast instructions
551 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
552 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000553
Chris Lattnera0e69692009-03-24 18:35:40 +0000554 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000555 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000556 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000557
558 // We don't want to form an inttoptr or ptrtoint that converts to an integer
559 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000560 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000561 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000562 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000563 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000564 Res = 0;
565
566 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000567}
568
569/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
570/// in any code being generated. It does not require codegen if V is simple
571/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000572static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
573 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000574 if (V->getType() == Ty || isa<Constant>(V)) return false;
575
Chris Lattner01575b72006-05-25 23:24:33 +0000576 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000577 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000578 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000579 return false;
580 return true;
581}
582
Chris Lattner4f98c562003-03-10 21:43:22 +0000583// SimplifyCommutative - This performs a few simplifications for commutative
584// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000585//
Chris Lattner4f98c562003-03-10 21:43:22 +0000586// 1. Order operands such that they are listed from right (least complex) to
587// left (most complex). This puts constants before unary operators before
588// binary operators.
589//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000590// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
591// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000592//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000593bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000594 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000595 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000596 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000597
Chris Lattner4f98c562003-03-10 21:43:22 +0000598 if (!I.isAssociative()) return Changed;
599 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000600 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
601 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
602 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000603 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000604 cast<Constant>(I.getOperand(1)),
605 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000606 I.setOperand(0, Op->getOperand(0));
607 I.setOperand(1, Folded);
608 return true;
609 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
610 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
611 isOnlyUse(Op) && isOnlyUse(Op1)) {
612 Constant *C1 = cast<Constant>(Op->getOperand(1));
613 Constant *C2 = cast<Constant>(Op1->getOperand(1));
614
615 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000616 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000617 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000618 Op1->getOperand(0),
619 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000620 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000621 I.setOperand(0, New);
622 I.setOperand(1, Folded);
623 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000624 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000625 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000626 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000627}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000628
Chris Lattner8d969642003-03-10 23:06:50 +0000629// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
630// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000631//
Dan Gohman186a6362009-08-12 16:04:34 +0000632static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000633 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000634 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000635
Chris Lattner0ce85802004-12-14 20:08:06 +0000636 // Constants can be considered to be negated values if they can be folded.
637 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000638 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000639
640 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
641 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000642 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000643
Chris Lattner8d969642003-03-10 23:06:50 +0000644 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000645}
646
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000647// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
648// instruction if the LHS is a constant negative zero (which is the 'negate'
649// form).
650//
Dan Gohman186a6362009-08-12 16:04:34 +0000651static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000652 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000653 return BinaryOperator::getFNegArgument(V);
654
655 // Constants can be considered to be negated values if they can be folded.
656 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000657 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000658
659 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
660 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000661 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000662
663 return 0;
664}
665
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000666/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
667/// returning the kind and providing the out parameter results if we
668/// successfully match.
669static SelectPatternFlavor
670MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
671 SelectInst *SI = dyn_cast<SelectInst>(V);
672 if (SI == 0) return SPF_UNKNOWN;
673
674 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
675 if (ICI == 0) return SPF_UNKNOWN;
676
677 LHS = ICI->getOperand(0);
678 RHS = ICI->getOperand(1);
679
680 // (icmp X, Y) ? X : Y
681 if (SI->getTrueValue() == ICI->getOperand(0) &&
682 SI->getFalseValue() == ICI->getOperand(1)) {
683 switch (ICI->getPredicate()) {
684 default: return SPF_UNKNOWN; // Equality.
685 case ICmpInst::ICMP_UGT:
686 case ICmpInst::ICMP_UGE: return SPF_UMAX;
687 case ICmpInst::ICMP_SGT:
688 case ICmpInst::ICMP_SGE: return SPF_SMAX;
689 case ICmpInst::ICMP_ULT:
690 case ICmpInst::ICMP_ULE: return SPF_UMIN;
691 case ICmpInst::ICMP_SLT:
692 case ICmpInst::ICMP_SLE: return SPF_SMIN;
693 }
694 }
695
696 // (icmp X, Y) ? Y : X
697 if (SI->getTrueValue() == ICI->getOperand(1) &&
698 SI->getFalseValue() == ICI->getOperand(0)) {
699 switch (ICI->getPredicate()) {
700 default: return SPF_UNKNOWN; // Equality.
701 case ICmpInst::ICMP_UGT:
702 case ICmpInst::ICMP_UGE: return SPF_UMIN;
703 case ICmpInst::ICMP_SGT:
704 case ICmpInst::ICMP_SGE: return SPF_SMIN;
705 case ICmpInst::ICMP_ULT:
706 case ICmpInst::ICMP_ULE: return SPF_UMAX;
707 case ICmpInst::ICMP_SLT:
708 case ICmpInst::ICMP_SLE: return SPF_SMAX;
709 }
710 }
711
712 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
713
714 return SPF_UNKNOWN;
715}
716
Chris Lattner48b59ec2009-10-26 15:40:07 +0000717/// isFreeToInvert - Return true if the specified value is free to invert (apply
718/// ~ to). This happens in cases where the ~ can be eliminated.
719static inline bool isFreeToInvert(Value *V) {
720 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000721 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000722 return true;
723
724 // Constants can be considered to be not'ed values.
725 if (isa<ConstantInt>(V))
726 return true;
727
728 // Compares can be inverted if they have a single use.
729 if (CmpInst *CI = dyn_cast<CmpInst>(V))
730 return CI->hasOneUse();
731
732 return false;
733}
734
735static inline Value *dyn_castNotVal(Value *V) {
736 // If this is not(not(x)) don't return that this is a not: we want the two
737 // not's to be folded first.
738 if (BinaryOperator::isNot(V)) {
739 Value *Operand = BinaryOperator::getNotArgument(V);
740 if (!isFreeToInvert(Operand))
741 return Operand;
742 }
Chris Lattner8d969642003-03-10 23:06:50 +0000743
744 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000745 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000746 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000747 return 0;
748}
749
Chris Lattner48b59ec2009-10-26 15:40:07 +0000750
751
Chris Lattnerc8802d22003-03-11 00:12:48 +0000752// dyn_castFoldableMul - If this value is a multiply that can be folded into
753// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000754// non-constant operand of the multiply, and set CST to point to the multiplier.
755// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000756//
Dan Gohman186a6362009-08-12 16:04:34 +0000757static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000758 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000759 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000760 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000761 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000762 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000763 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000764 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000765 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000766 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000767 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000768 CST = ConstantInt::get(V->getType()->getContext(),
769 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000770 return I->getOperand(0);
771 }
772 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000773 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000774}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000775
Reid Spencer7177c3a2007-03-25 05:33:51 +0000776/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000777static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000778 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000779 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000780}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000781/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000782static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000783 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000784 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000785}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000786/// MultiplyOverflows - True if the multiply can not be expressed in an int
787/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000788static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000789 uint32_t W = C1->getBitWidth();
790 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
791 if (sign) {
792 LHSExt.sext(W * 2);
793 RHSExt.sext(W * 2);
794 } else {
795 LHSExt.zext(W * 2);
796 RHSExt.zext(W * 2);
797 }
798
799 APInt MulExt = LHSExt * RHSExt;
800
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000801 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000802 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000803
804 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
805 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
806 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000807}
Chris Lattner955f3312004-09-28 21:48:02 +0000808
Reid Spencere7816b52007-03-08 01:52:58 +0000809
Chris Lattner255d8912006-02-11 09:31:47 +0000810/// ShrinkDemandedConstant - Check to see if the specified operand of the
811/// specified instruction is a constant integer. If so, check to see if there
812/// are any bits set in the constant that are not demanded. If so, shrink the
813/// constant and return true.
814static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000815 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000816 assert(I && "No instruction?");
817 assert(OpNo < I->getNumOperands() && "Operand index too large");
818
819 // If the operand is not a constant integer, nothing to do.
820 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
821 if (!OpC) return false;
822
823 // If there are no bits set that aren't demanded, nothing to do.
824 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
825 if ((~Demanded & OpC->getValue()) == 0)
826 return false;
827
828 // This instruction is producing bits that are not demanded. Shrink the RHS.
829 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000830 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000831 return true;
832}
833
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000834// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
835// set of known zero and one bits, compute the maximum and minimum values that
836// could have the specified known zero and known one bits, returning them in
837// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000838static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000839 const APInt& KnownOne,
840 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000841 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
842 KnownZero.getBitWidth() == Min.getBitWidth() &&
843 KnownZero.getBitWidth() == Max.getBitWidth() &&
844 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000845 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000846
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000847 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
848 // bit if it is unknown.
849 Min = KnownOne;
850 Max = KnownOne|UnknownBits;
851
Dan Gohman1c8491e2009-04-25 17:12:48 +0000852 if (UnknownBits.isNegative()) { // Sign bit is unknown
853 Min.set(Min.getBitWidth()-1);
854 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000855 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000856}
857
858// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
859// a set of known zero and one bits, compute the maximum and minimum values that
860// could have the specified known zero and known one bits, returning them in
861// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000862static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000863 const APInt &KnownOne,
864 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000865 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
866 KnownZero.getBitWidth() == Min.getBitWidth() &&
867 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000868 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000869 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000870
871 // The minimum value is when the unknown bits are all zeros.
872 Min = KnownOne;
873 // The maximum value is when the unknown bits are all ones.
874 Max = KnownOne|UnknownBits;
875}
Chris Lattner255d8912006-02-11 09:31:47 +0000876
Chris Lattner886ab6c2009-01-31 08:15:18 +0000877/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
878/// SimplifyDemandedBits knows about. See if the instruction has any
879/// properties that allow us to simplify its operands.
880bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000881 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000882 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
883 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
884
885 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
886 KnownZero, KnownOne, 0);
887 if (V == 0) return false;
888 if (V == &Inst) return true;
889 ReplaceInstUsesWith(Inst, V);
890 return true;
891}
892
893/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
894/// specified instruction operand if possible, updating it in place. It returns
895/// true if it made any change and false otherwise.
896bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
897 APInt &KnownZero, APInt &KnownOne,
898 unsigned Depth) {
899 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
900 KnownZero, KnownOne, Depth);
901 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000902 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000903 return true;
904}
905
906
907/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
908/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000909/// that only the bits set in DemandedMask of the result of V are ever used
910/// downstream. Consequently, depending on the mask and V, it may be possible
911/// to replace V with a constant or one of its operands. In such cases, this
912/// function does the replacement and returns true. In all other cases, it
913/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000914/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000915/// to be zero in the expression. These are provided to potentially allow the
916/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
917/// the expression. KnownOne and KnownZero always follow the invariant that
918/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
919/// the bits in KnownOne and KnownZero may only be accurate for those bits set
920/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
921/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000922///
923/// This returns null if it did not change anything and it permits no
924/// simplification. This returns V itself if it did some simplification of V's
925/// operands based on the information about what bits are demanded. This returns
926/// some other non-null value if it found out that V is equal to another value
927/// in the context where the specified bits are demanded, but not for all users.
928Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
929 APInt &KnownZero, APInt &KnownOne,
930 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000931 assert(V != 0 && "Null pointer of Value???");
932 assert(Depth <= 6 && "Limit Search Depth");
933 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000934 const Type *VTy = V->getType();
935 assert((TD || !isa<PointerType>(VTy)) &&
936 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000937 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
938 (!VTy->isIntOrIntVector() ||
939 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000940 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000941 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000942 "Value *V, DemandedMask, KnownZero and KnownOne "
943 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000944 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
945 // We know all of the bits for a constant!
946 KnownOne = CI->getValue() & DemandedMask;
947 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000949 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000950 if (isa<ConstantPointerNull>(V)) {
951 // We know all of the bits for a constant!
952 KnownOne.clear();
953 KnownZero = DemandedMask;
954 return 0;
955 }
956
Chris Lattner08d2cc72009-01-31 07:26:06 +0000957 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000958 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000959 if (DemandedMask == 0) { // Not demanding any bits from V.
960 if (isa<UndefValue>(V))
961 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000962 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000963 }
964
Chris Lattner4598c942009-01-31 08:24:16 +0000965 if (Depth == 6) // Limit search depth.
966 return 0;
967
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000968 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
969 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
970
Dan Gohman1c8491e2009-04-25 17:12:48 +0000971 Instruction *I = dyn_cast<Instruction>(V);
972 if (!I) {
973 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
974 return 0; // Only analyze instructions.
975 }
976
Chris Lattner4598c942009-01-31 08:24:16 +0000977 // If there are multiple uses of this value and we aren't at the root, then
978 // we can't do any simplifications of the operands, because DemandedMask
979 // only reflects the bits demanded by *one* of the users.
980 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000981 // Despite the fact that we can't simplify this instruction in all User's
982 // context, we can at least compute the knownzero/knownone bits, and we can
983 // do simplifications that apply to *just* the one user if we know that
984 // this instruction has a simpler value in that context.
985 if (I->getOpcode() == Instruction::And) {
986 // If either the LHS or the RHS are Zero, the result is zero.
987 ComputeMaskedBits(I->getOperand(1), DemandedMask,
988 RHSKnownZero, RHSKnownOne, Depth+1);
989 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
990 LHSKnownZero, LHSKnownOne, Depth+1);
991
992 // If all of the demanded bits are known 1 on one side, return the other.
993 // These bits cannot contribute to the result of the 'and' in this
994 // context.
995 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
996 (DemandedMask & ~LHSKnownZero))
997 return I->getOperand(0);
998 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
999 (DemandedMask & ~RHSKnownZero))
1000 return I->getOperand(1);
1001
1002 // If all of the demanded bits in the inputs are known zeros, return zero.
1003 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001004 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +00001005
1006 } else if (I->getOpcode() == Instruction::Or) {
1007 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1008 // only bits from X or Y are demanded.
1009
1010 // If either the LHS or the RHS are One, the result is One.
1011 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1012 RHSKnownZero, RHSKnownOne, Depth+1);
1013 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1014 LHSKnownZero, LHSKnownOne, Depth+1);
1015
1016 // If all of the demanded bits are known zero on one side, return the
1017 // other. These bits cannot contribute to the result of the 'or' in this
1018 // context.
1019 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1020 (DemandedMask & ~LHSKnownOne))
1021 return I->getOperand(0);
1022 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1023 (DemandedMask & ~RHSKnownOne))
1024 return I->getOperand(1);
1025
1026 // If all of the potentially set bits on one side are known to be set on
1027 // the other side, just use the 'other' side.
1028 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1029 (DemandedMask & (~RHSKnownZero)))
1030 return I->getOperand(0);
1031 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1032 (DemandedMask & (~LHSKnownZero)))
1033 return I->getOperand(1);
1034 }
1035
Chris Lattner4598c942009-01-31 08:24:16 +00001036 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1037 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1038 return 0;
1039 }
1040
1041 // If this is the root being simplified, allow it to have multiple uses,
1042 // just set the DemandedMask to all bits so that we can try to simplify the
1043 // operands. This allows visitTruncInst (for example) to simplify the
1044 // operand of a trunc without duplicating all the logic below.
1045 if (Depth == 0 && !V->hasOneUse())
1046 DemandedMask = APInt::getAllOnesValue(BitWidth);
1047
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001049 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +00001051 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001052 case Instruction::And:
1053 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1055 RHSKnownZero, RHSKnownOne, Depth+1) ||
1056 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001058 return I;
1059 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1060 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001061
1062 // If all of the demanded bits are known 1 on one side, return the other.
1063 // These bits cannot contribute to the result of the 'and'.
1064 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1065 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001066 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001067 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1068 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001070
1071 // If all of the demanded bits in the inputs are known zeros, return zero.
1072 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001073 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001074
1075 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001076 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001077 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001078
1079 // Output known-1 bits are only known if set in both the LHS & RHS.
1080 RHSKnownOne &= LHSKnownOne;
1081 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1082 RHSKnownZero |= LHSKnownZero;
1083 break;
1084 case Instruction::Or:
1085 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001086 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1087 RHSKnownZero, RHSKnownOne, Depth+1) ||
1088 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001090 return I;
1091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1092 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001093
1094 // If all of the demanded bits are known zero on one side, return the other.
1095 // These bits cannot contribute to the result of the 'or'.
1096 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1097 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001098 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1100 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001101 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001102
1103 // If all of the potentially set bits on one side are known to be set on
1104 // the other side, just use the 'other' side.
1105 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1106 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1109 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001111
1112 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001113 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001114 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001115
1116 // Output known-0 bits are only known if clear in both the LHS & RHS.
1117 RHSKnownZero &= LHSKnownZero;
1118 // Output known-1 are known to be set if set in either the LHS | RHS.
1119 RHSKnownOne |= LHSKnownOne;
1120 break;
1121 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1123 RHSKnownZero, RHSKnownOne, Depth+1) ||
1124 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 return I;
1127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1128 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001129
1130 // If all of the demanded bits are known zero on one side, return the other.
1131 // These bits cannot contribute to the result of the 'xor'.
1132 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001133 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001134 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001135 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001136
1137 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1138 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1139 (RHSKnownOne & LHSKnownOne);
1140 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1141 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1142 (RHSKnownOne & LHSKnownZero);
1143
1144 // If all of the demanded bits are known to be zero on one side or the
1145 // other, turn this into an *inclusive* or.
1146 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001147 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1148 Instruction *Or =
1149 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1150 I->getName());
1151 return InsertNewInstBefore(Or, *I);
1152 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001153
1154 // If all of the demanded bits on one side are known, and all of the set
1155 // bits on that side are also known to be set on the other side, turn this
1156 // into an AND, as we know the bits will be cleared.
1157 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1158 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1159 // all known
1160 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001161 Constant *AndC = Constant::getIntegerValue(VTy,
1162 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001163 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001164 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001165 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 }
1167 }
1168
1169 // If the RHS is a constant, see if we can simplify it.
1170 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001171 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001172 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001173
Chris Lattnerd0883142009-10-11 22:22:13 +00001174 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1175 // are flipping are known to be set, then the xor is just resetting those
1176 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1177 // simplifying both of them.
1178 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1179 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1180 isa<ConstantInt>(I->getOperand(1)) &&
1181 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1182 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1183 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1184 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1185 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1186
1187 Constant *AndC =
1188 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1189 Instruction *NewAnd =
1190 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1191 InsertNewInstBefore(NewAnd, *I);
1192
1193 Constant *XorC =
1194 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1195 Instruction *NewXor =
1196 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1197 return InsertNewInstBefore(NewXor, *I);
1198 }
1199
1200
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 RHSKnownZero = KnownZeroOut;
1202 RHSKnownOne = KnownOneOut;
1203 break;
1204 }
1205 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001206 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1207 RHSKnownZero, RHSKnownOne, Depth+1) ||
1208 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001210 return I;
1211 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1212 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001213
1214 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001215 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1216 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001217 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001218
1219 // Only known if known in both the LHS and RHS.
1220 RHSKnownOne &= LHSKnownOne;
1221 RHSKnownZero &= LHSKnownZero;
1222 break;
1223 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001224 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001225 DemandedMask.zext(truncBf);
1226 RHSKnownZero.zext(truncBf);
1227 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001229 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001230 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 DemandedMask.trunc(BitWidth);
1232 RHSKnownZero.trunc(BitWidth);
1233 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001234 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 break;
1236 }
1237 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001238 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001240
1241 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1242 if (const VectorType *SrcVTy =
1243 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1244 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1245 // Don't touch a bitcast between vectors of different element counts.
1246 return false;
1247 } else
1248 // Don't touch a scalar-to-vector bitcast.
1249 return false;
1250 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1251 // Don't touch a vector-to-scalar bitcast.
1252 return false;
1253
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
1257 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 break;
1259 case Instruction::ZExt: {
1260 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001261 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001262
Zhou Shengd48653a2007-03-29 04:45:55 +00001263 DemandedMask.trunc(SrcBitWidth);
1264 RHSKnownZero.trunc(SrcBitWidth);
1265 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001266 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 DemandedMask.zext(BitWidth);
1270 RHSKnownZero.zext(BitWidth);
1271 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001274 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 break;
1276 }
1277 case Instruction::SExt: {
1278 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001279 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001280
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001282 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001283
Zhou Sheng01542f32007-03-29 02:26:30 +00001284 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 // If any of the sign extended bits are demanded, we know that the sign
1286 // bit is demanded.
1287 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001288 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001289
Zhou Shengd48653a2007-03-29 04:45:55 +00001290 InputDemandedBits.trunc(SrcBitWidth);
1291 RHSKnownZero.trunc(SrcBitWidth);
1292 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001293 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001294 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001295 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001296 InputDemandedBits.zext(BitWidth);
1297 RHSKnownZero.zext(BitWidth);
1298 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001299 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001300
1301 // If the sign bit of the input is known set or clear, then we know the
1302 // top bits of the result.
1303
1304 // If the input sign bit is known zero, or if the NewBits are not demanded
1305 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001306 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1309 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001310 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 }
1313 break;
1314 }
1315 case Instruction::Add: {
1316 // Figure out what the input bits are. If the top bits of the and result
1317 // are not demanded, then the add doesn't demand them from its input
1318 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001319 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001320
1321 // If there is a constant on the RHS, there are a variety of xformations
1322 // we can do.
1323 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1324 // If null, this should be simplified elsewhere. Some of the xforms here
1325 // won't work if the RHS is zero.
1326 if (RHS->isZero())
1327 break;
1328
1329 // If the top bit of the output is demanded, demand everything from the
1330 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001331 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001332
1333 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001334 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001335 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001336 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001337
1338 // If the RHS of the add has bits set that can't affect the input, reduce
1339 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001340 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001342
1343 // Avoid excess work.
1344 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1345 break;
1346
1347 // Turn it into OR if input bits are zero.
1348 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1349 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001350 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001353 }
1354
1355 // We can say something about the output known-zero and known-one bits,
1356 // depending on potential carries from the input constant and the
1357 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1358 // bits set and the RHS constant is 0x01001, then we know we have a known
1359 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1360
1361 // To compute this, we first compute the potential carry bits. These are
1362 // the bits which may be modified. I'm not aware of a better way to do
1363 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001365 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001366
1367 // Now that we know which bits have carries, compute the known-1/0 sets.
1368
1369 // Bits are known one if they are known zero in one operand and one in the
1370 // other, and there is no input carry.
1371 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1372 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1373
1374 // Bits are known zero if they are known zero in both operands and there
1375 // is no input carry.
1376 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1377 } else {
1378 // If the high-bits of this ADD are not demanded, then it does not demand
1379 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001380 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001381 // Right fill the mask of bits for this ADD to demand the most
1382 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001383 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001384 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1385 LHSKnownZero, LHSKnownOne, Depth+1) ||
1386 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001387 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001388 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001389 }
1390 }
1391 break;
1392 }
1393 case Instruction::Sub:
1394 // If the high-bits of this SUB are not demanded, then it does not demand
1395 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001396 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001397 // Right fill the mask of bits for this SUB to demand the most
1398 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001399 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001400 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001401 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1402 LHSKnownZero, LHSKnownOne, Depth+1) ||
1403 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001404 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001405 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001406 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001407 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1408 // the known zeros and ones.
1409 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 break;
1411 case Instruction::Shl:
1412 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001413 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001414 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001415 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001416 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001417 return I;
1418 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001419 RHSKnownZero <<= ShiftAmt;
1420 RHSKnownOne <<= ShiftAmt;
1421 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001422 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001423 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001424 }
1425 break;
1426 case Instruction::LShr:
1427 // For a logical shift right
1428 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001429 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001430
Reid Spencer8cb68342007-03-12 17:25:59 +00001431 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001432 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001433 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001434 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001435 return I;
1436 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1438 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001439 if (ShiftAmt) {
1440 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001441 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001442 RHSKnownZero |= HighBits; // high bits known zero.
1443 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001444 }
1445 break;
1446 case Instruction::AShr:
1447 // If this is an arithmetic shift right and only the low-bit is set, we can
1448 // always convert this into a logical shr, even if the shift amount is
1449 // variable. The low bit of the shift cannot be an input sign bit unless
1450 // the shift amount is >= the size of the datatype, which is undefined.
1451 if (DemandedMask == 1) {
1452 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001453 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001454 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001455 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001456 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001457
1458 // If the sign bit is the only bit demanded by this ashr, then there is no
1459 // need to do it, the shift doesn't change the high bit.
1460 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001461 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001462
1463 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001464 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001465
Reid Spencer8cb68342007-03-12 17:25:59 +00001466 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001467 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001468 // If any of the "high bits" are demanded, we should set the sign bit as
1469 // demanded.
1470 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1471 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001472 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001473 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001474 return I;
1475 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001476 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001477 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001478 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1479 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1480
1481 // Handle the sign bits.
1482 APInt SignBit(APInt::getSignBit(BitWidth));
1483 // Adjust to where it is now in the mask.
1484 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1485
1486 // If the input sign bit is known to be zero, or if none of the top bits
1487 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001488 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001489 (HighBits & ~DemandedMask) == HighBits) {
1490 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001491 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001492 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001493 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001494 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1495 RHSKnownOne |= HighBits;
1496 }
1497 }
1498 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001499 case Instruction::SRem:
1500 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001501 APInt RA = Rem->getValue().abs();
1502 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001503 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001504 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001505
Nick Lewycky8e394322008-11-02 02:41:50 +00001506 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001507 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001508 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001509 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001510 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001511
1512 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1513 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001514
1515 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001516
Chris Lattner886ab6c2009-01-31 08:15:18 +00001517 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001518 }
1519 }
1520 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001521 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001522 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1523 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001524 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1525 KnownZero2, KnownOne2, Depth+1) ||
1526 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001527 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001528 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001529
Chris Lattner455e9ab2009-01-21 18:09:24 +00001530 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001531 Leaders = std::max(Leaders,
1532 KnownZero2.countLeadingOnes());
1533 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001534 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001535 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001536 case Instruction::Call:
1537 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1538 switch (II->getIntrinsicID()) {
1539 default: break;
1540 case Intrinsic::bswap: {
1541 // If the only bits demanded come from one byte of the bswap result,
1542 // just shift the input byte into position to eliminate the bswap.
1543 unsigned NLZ = DemandedMask.countLeadingZeros();
1544 unsigned NTZ = DemandedMask.countTrailingZeros();
1545
1546 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1547 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1548 // have 14 leading zeros, round to 8.
1549 NLZ &= ~7;
1550 NTZ &= ~7;
1551 // If we need exactly one byte, we can do this transformation.
1552 if (BitWidth-NLZ-NTZ == 8) {
1553 unsigned ResultBit = NTZ;
1554 unsigned InputBit = BitWidth-NTZ-8;
1555
1556 // Replace this with either a left or right shift to get the byte into
1557 // the right place.
1558 Instruction *NewVal;
1559 if (InputBit > ResultBit)
1560 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001561 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001562 else
1563 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001564 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001565 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001566 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001567 }
1568
1569 // TODO: Could compute known zero/one bits based on the input.
1570 break;
1571 }
1572 }
1573 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001574 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001575 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001576 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001577
1578 // If the client is only demanding bits that we know, return the known
1579 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001580 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1581 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001582 return false;
1583}
1584
Chris Lattner867b99f2006-10-05 06:55:50 +00001585
Mon P Wangaeb06d22008-11-10 04:46:22 +00001586/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001587/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001588/// actually used by the caller. This method analyzes which elements of the
1589/// operand are undef and returns that information in UndefElts.
1590///
1591/// If the information about demanded elements can be used to simplify the
1592/// operation, the operation is simplified, then the resultant value is
1593/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001594Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1595 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001596 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001597 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001598 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001599 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001600
1601 if (isa<UndefValue>(V)) {
1602 // If the entire vector is undefined, just return this info.
1603 UndefElts = EltMask;
1604 return 0;
1605 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1606 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001607 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001608 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001609
Chris Lattner867b99f2006-10-05 06:55:50 +00001610 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001611 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1612 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001613 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001614
1615 std::vector<Constant*> Elts;
1616 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001617 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001618 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001619 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001620 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1621 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001622 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001623 } else { // Otherwise, defined.
1624 Elts.push_back(CP->getOperand(i));
1625 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001626
Chris Lattner867b99f2006-10-05 06:55:50 +00001627 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001628 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001629 return NewCP != CP ? NewCP : 0;
1630 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001631 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001632 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001633
1634 // Check if this is identity. If so, return 0 since we are not simplifying
1635 // anything.
1636 if (DemandedElts == ((1ULL << VWidth) -1))
1637 return 0;
1638
Reid Spencer9d6565a2007-02-15 02:26:10 +00001639 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001640 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001641 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001642 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001643 for (unsigned i = 0; i != VWidth; ++i) {
1644 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1645 Elts.push_back(Elt);
1646 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001647 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001648 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001649 }
1650
Dan Gohman488fbfc2008-09-09 18:11:14 +00001651 // Limit search depth.
1652 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001653 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001654
1655 // If multiple users are using the root value, procede with
1656 // simplification conservatively assuming that all elements
1657 // are needed.
1658 if (!V->hasOneUse()) {
1659 // Quit if we find multiple users of a non-root value though.
1660 // They'll be handled when it's their turn to be visited by
1661 // the main instcombine process.
1662 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001663 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001664 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001665
1666 // Conservatively assume that all elements are needed.
1667 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001668 }
1669
1670 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001671 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001672
1673 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001674 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001675 Value *TmpV;
1676 switch (I->getOpcode()) {
1677 default: break;
1678
1679 case Instruction::InsertElement: {
1680 // If this is a variable index, we don't know which element it overwrites.
1681 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001682 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001683 if (Idx == 0) {
1684 // Note that we can't propagate undef elt info, because we don't know
1685 // which elt is getting updated.
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1687 UndefElts2, Depth+1);
1688 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1689 break;
1690 }
1691
1692 // If this is inserting an element that isn't demanded, remove this
1693 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001694 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001695 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1696 Worklist.Add(I);
1697 return I->getOperand(0);
1698 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001699
1700 // Otherwise, the element inserted overwrites whatever was there, so the
1701 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001702 APInt DemandedElts2 = DemandedElts;
1703 DemandedElts2.clear(IdxNo);
1704 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001705 UndefElts, Depth+1);
1706 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1707
1708 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001709 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001710 break;
1711 }
1712 case Instruction::ShuffleVector: {
1713 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001714 uint64_t LHSVWidth =
1715 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001716 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001717 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001718 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001719 unsigned MaskVal = Shuffle->getMaskValue(i);
1720 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001721 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001722 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001723 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001724 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001725 else
Evan Cheng388df622009-02-03 10:05:09 +00001726 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001727 }
1728 }
1729 }
1730
Nate Begeman7b254672009-02-11 22:36:25 +00001731 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001732 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001733 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001734 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1735
Nate Begeman7b254672009-02-11 22:36:25 +00001736 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001737 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1738 UndefElts3, Depth+1);
1739 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1740
1741 bool NewUndefElts = false;
1742 for (unsigned i = 0; i < VWidth; i++) {
1743 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001744 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001745 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001746 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001747 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001748 NewUndefElts = true;
1749 UndefElts.set(i);
1750 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001751 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001752 if (UndefElts3[MaskVal - LHSVWidth]) {
1753 NewUndefElts = true;
1754 UndefElts.set(i);
1755 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001756 }
1757 }
1758
1759 if (NewUndefElts) {
1760 // Add additional discovered undefs.
1761 std::vector<Constant*> Elts;
1762 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001763 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001764 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001765 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001766 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001767 Shuffle->getMaskValue(i)));
1768 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001769 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001770 MadeChange = true;
1771 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001772 break;
1773 }
Chris Lattner69878332007-04-14 22:29:23 +00001774 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001775 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001776 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1777 if (!VTy) break;
1778 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001779 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001780 unsigned Ratio;
1781
1782 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001783 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001784 // elements as are demanded of us.
1785 Ratio = 1;
1786 InputDemandedElts = DemandedElts;
1787 } else if (VWidth > InVWidth) {
1788 // Untested so far.
1789 break;
1790
1791 // If there are more elements in the result than there are in the source,
1792 // then an input element is live if any of the corresponding output
1793 // elements are live.
1794 Ratio = VWidth/InVWidth;
1795 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001796 if (DemandedElts[OutIdx])
1797 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001798 }
1799 } else {
1800 // Untested so far.
1801 break;
1802
1803 // If there are more elements in the source than there are in the result,
1804 // then an input element is live if the corresponding output element is
1805 // live.
1806 Ratio = InVWidth/VWidth;
1807 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001808 if (DemandedElts[InIdx/Ratio])
1809 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001810 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001811
Chris Lattner69878332007-04-14 22:29:23 +00001812 // div/rem demand all inputs, because they don't want divide by zero.
1813 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1814 UndefElts2, Depth+1);
1815 if (TmpV) {
1816 I->setOperand(0, TmpV);
1817 MadeChange = true;
1818 }
1819
1820 UndefElts = UndefElts2;
1821 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001822 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001823 // If there are more elements in the result than there are in the source,
1824 // then an output element is undef if the corresponding input element is
1825 // undef.
1826 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001827 if (UndefElts2[OutIdx/Ratio])
1828 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001829 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001830 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001831 // If there are more elements in the source than there are in the result,
1832 // then a result element is undef if all of the corresponding input
1833 // elements are undef.
1834 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1835 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001836 if (!UndefElts2[InIdx]) // Not undef?
1837 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001838 }
1839 break;
1840 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001841 case Instruction::And:
1842 case Instruction::Or:
1843 case Instruction::Xor:
1844 case Instruction::Add:
1845 case Instruction::Sub:
1846 case Instruction::Mul:
1847 // div/rem demand all inputs, because they don't want divide by zero.
1848 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1849 UndefElts, Depth+1);
1850 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1851 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1852 UndefElts2, Depth+1);
1853 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1854
1855 // Output elements are undefined if both are undefined. Consider things
1856 // like undef&0. The result is known zero, not undef.
1857 UndefElts &= UndefElts2;
1858 break;
1859
1860 case Instruction::Call: {
1861 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1862 if (!II) break;
1863 switch (II->getIntrinsicID()) {
1864 default: break;
1865
1866 // Binary vector operations that work column-wise. A dest element is a
1867 // function of the corresponding input elements from the two inputs.
1868 case Intrinsic::x86_sse_sub_ss:
1869 case Intrinsic::x86_sse_mul_ss:
1870 case Intrinsic::x86_sse_min_ss:
1871 case Intrinsic::x86_sse_max_ss:
1872 case Intrinsic::x86_sse2_sub_sd:
1873 case Intrinsic::x86_sse2_mul_sd:
1874 case Intrinsic::x86_sse2_min_sd:
1875 case Intrinsic::x86_sse2_max_sd:
1876 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1877 UndefElts, Depth+1);
1878 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1879 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1880 UndefElts2, Depth+1);
1881 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1882
1883 // If only the low elt is demanded and this is a scalarizable intrinsic,
1884 // scalarize it now.
1885 if (DemandedElts == 1) {
1886 switch (II->getIntrinsicID()) {
1887 default: break;
1888 case Intrinsic::x86_sse_sub_ss:
1889 case Intrinsic::x86_sse_mul_ss:
1890 case Intrinsic::x86_sse2_sub_sd:
1891 case Intrinsic::x86_sse2_mul_sd:
1892 // TODO: Lower MIN/MAX/ABS/etc
1893 Value *LHS = II->getOperand(1);
1894 Value *RHS = II->getOperand(2);
1895 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001896 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001897 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001898 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001899 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001900
1901 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001902 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001903 case Intrinsic::x86_sse_sub_ss:
1904 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001905 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001906 II->getName()), *II);
1907 break;
1908 case Intrinsic::x86_sse_mul_ss:
1909 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001910 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001911 II->getName()), *II);
1912 break;
1913 }
1914
1915 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001916 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001917 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001918 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001919 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001920 return New;
1921 }
1922 }
1923
1924 // Output elements are undefined if both are undefined. Consider things
1925 // like undef&0. The result is known zero, not undef.
1926 UndefElts &= UndefElts2;
1927 break;
1928 }
1929 break;
1930 }
1931 }
1932 return MadeChange ? I : 0;
1933}
1934
Dan Gohman45b4e482008-05-19 22:14:15 +00001935
Chris Lattner564a7272003-08-13 19:01:45 +00001936/// AssociativeOpt - Perform an optimization on an associative operator. This
1937/// function is designed to check a chain of associative operators for a
1938/// potential to apply a certain optimization. Since the optimization may be
1939/// applicable if the expression was reassociated, this checks the chain, then
1940/// reassociates the expression as necessary to expose the optimization
1941/// opportunity. This makes use of a special Functor, which must define
1942/// 'shouldApply' and 'apply' methods.
1943///
1944template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001945static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001946 unsigned Opcode = Root.getOpcode();
1947 Value *LHS = Root.getOperand(0);
1948
1949 // Quick check, see if the immediate LHS matches...
1950 if (F.shouldApply(LHS))
1951 return F.apply(Root);
1952
1953 // Otherwise, if the LHS is not of the same opcode as the root, return.
1954 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001955 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001956 // Should we apply this transform to the RHS?
1957 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1958
1959 // If not to the RHS, check to see if we should apply to the LHS...
1960 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1961 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1962 ShouldApply = true;
1963 }
1964
1965 // If the functor wants to apply the optimization to the RHS of LHSI,
1966 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1967 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001968 // Now all of the instructions are in the current basic block, go ahead
1969 // and perform the reassociation.
1970 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1971
1972 // First move the selected RHS to the LHS of the root...
1973 Root.setOperand(0, LHSI->getOperand(1));
1974
1975 // Make what used to be the LHS of the root be the user of the root...
1976 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001977 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001978 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001979 return 0;
1980 }
Chris Lattner65725312004-04-16 18:08:07 +00001981 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001982 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001983 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001984 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001985 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001986
1987 // Now propagate the ExtraOperand down the chain of instructions until we
1988 // get to LHSI.
1989 while (TmpLHSI != LHSI) {
1990 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001991 // Move the instruction to immediately before the chain we are
1992 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001993 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001994 ARI = NextLHSI;
1995
Chris Lattner564a7272003-08-13 19:01:45 +00001996 Value *NextOp = NextLHSI->getOperand(1);
1997 NextLHSI->setOperand(1, ExtraOperand);
1998 TmpLHSI = NextLHSI;
1999 ExtraOperand = NextOp;
2000 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002001
Chris Lattner564a7272003-08-13 19:01:45 +00002002 // Now that the instructions are reassociated, have the functor perform
2003 // the transformation...
2004 return F.apply(Root);
2005 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002006
Chris Lattner564a7272003-08-13 19:01:45 +00002007 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2008 }
2009 return 0;
2010}
2011
Dan Gohman844731a2008-05-13 00:00:25 +00002012namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002013
Nick Lewycky02d639f2008-05-23 04:34:58 +00002014// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002015struct AddRHS {
2016 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00002017 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002018 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2019 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002020 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00002021 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002022 }
2023};
2024
2025// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2026// iff C1&C2 == 0
2027struct AddMaskingAnd {
2028 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00002029 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002030 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002031 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00002032 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002033 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002034 }
2035 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002036 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002037 }
2038};
2039
Dan Gohman844731a2008-05-13 00:00:25 +00002040}
2041
Chris Lattner6e7ba452005-01-01 16:22:27 +00002042static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002043 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00002044 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00002045 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00002046
Chris Lattner2eefe512004-04-09 19:05:30 +00002047 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002048 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2049 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002050
Chris Lattner2eefe512004-04-09 19:05:30 +00002051 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2052 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00002053 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2054 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002055 }
2056
2057 Value *Op0 = SO, *Op1 = ConstOperand;
2058 if (!ConstIsRHS)
2059 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00002060
Chris Lattner6e7ba452005-01-01 16:22:27 +00002061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00002062 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2063 SO->getName()+".op");
2064 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2065 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2066 SO->getName()+".cmp");
2067 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2068 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2069 SO->getName()+".cmp");
2070 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002071}
2072
2073// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2074// constant as the other operand, try to fold the binary operator into the
2075// select arguments. This also works for Cast instructions, which obviously do
2076// not have a second operand.
2077static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2078 InstCombiner *IC) {
2079 // Don't modify shared select instructions
2080 if (!SI->hasOneUse()) return 0;
2081 Value *TV = SI->getOperand(1);
2082 Value *FV = SI->getOperand(2);
2083
2084 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002085 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002086 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002087
Chris Lattner6e7ba452005-01-01 16:22:27 +00002088 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2089 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2090
Gabor Greif051a9502008-04-06 20:25:17 +00002091 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2092 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002093 }
2094 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002095}
2096
Chris Lattner4e998b22004-09-29 05:07:12 +00002097
Chris Lattner5d1704d2009-09-27 19:57:57 +00002098/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2099/// has a PHI node as operand #0, see if we can fold the instruction into the
2100/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002101///
2102/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2103/// that would normally be unprofitable because they strongly encourage jump
2104/// threading.
2105Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2106 bool AllowAggressive) {
2107 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002108 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002109 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002110 if (NumPHIValues == 0 ||
2111 // We normally only transform phis with a single use, unless we're trying
2112 // hard to make jump threading happen.
2113 (!PN->hasOneUse() && !AllowAggressive))
2114 return 0;
2115
2116
Chris Lattner5d1704d2009-09-27 19:57:57 +00002117 // Check to see if all of the operands of the PHI are simple constants
2118 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002119 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2120 // bail out. We don't do arbitrary constant expressions here because moving
2121 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002122 BasicBlock *NonConstBB = 0;
2123 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002124 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2125 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002126 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002127 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002128 NonConstBB = PN->getIncomingBlock(i);
2129
2130 // If the incoming non-constant value is in I's block, we have an infinite
2131 // loop.
2132 if (NonConstBB == I.getParent())
2133 return 0;
2134 }
2135
2136 // If there is exactly one non-constant value, we can insert a copy of the
2137 // operation in that block. However, if this is a critical edge, we would be
2138 // inserting the computation one some other paths (e.g. inside a loop). Only
2139 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002140 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002141 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2142 if (!BI || !BI->isUnconditional()) return 0;
2143 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002144
2145 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002146 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002147 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002148 InsertNewInstBefore(NewPN, *PN);
2149 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002150
2151 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002152 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2153 // We only currently try to fold the condition of a select when it is a phi,
2154 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002155 Value *TrueV = SI->getTrueValue();
2156 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002157 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002158 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002159 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002160 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2161 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002162 Value *InV = 0;
2163 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002164 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002165 } else {
2166 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002167 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2168 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002169 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002170 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002171 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002172 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002173 }
2174 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002175 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002176 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002177 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002178 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002179 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002180 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002181 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002182 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002183 } else {
2184 assert(PN->getIncomingBlock(i) == NonConstBB);
2185 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002186 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002187 PN->getIncomingValue(i), C, "phitmp",
2188 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002189 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002190 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002191 CI->getPredicate(),
2192 PN->getIncomingValue(i), C, "phitmp",
2193 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002194 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002195 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002196
2197 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002198 }
2199 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002200 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002201 } else {
2202 CastInst *CI = cast<CastInst>(&I);
2203 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002204 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002205 Value *InV;
2206 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002207 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002208 } else {
2209 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002210 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002211 I.getType(), "phitmp",
2212 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002213 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002214 }
2215 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002216 }
2217 }
2218 return ReplaceInstUsesWith(I, NewPN);
2219}
2220
Chris Lattner2454a2e2008-01-29 06:52:45 +00002221
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002222/// WillNotOverflowSignedAdd - Return true if we can prove that:
2223/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2224/// This basically requires proving that the add in the original type would not
2225/// overflow to change the sign bit or have a carry out.
2226bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2227 // There are different heuristics we can use for this. Here are some simple
2228 // ones.
2229
2230 // Add has the property that adding any two 2's complement numbers can only
2231 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002232 // have at least two sign bits, we know that the addition of the two values
2233 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002234 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2235 return true;
2236
2237
2238 // If one of the operands only has one non-zero bit, and if the other operand
2239 // has a known-zero bit in a more significant place than it (not including the
2240 // sign bit) the ripple may go up to and fill the zero, but won't change the
2241 // sign. For example, (X & ~4) + 1.
2242
2243 // TODO: Implement.
2244
2245 return false;
2246}
2247
Chris Lattner2454a2e2008-01-29 06:52:45 +00002248
Chris Lattner7e708292002-06-25 16:13:24 +00002249Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002250 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002251 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002252
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002253 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2254 I.hasNoUnsignedWrap(), TD))
2255 return ReplaceInstUsesWith(I, V);
2256
2257
Chris Lattner66331a42004-04-10 22:01:55 +00002258 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002259 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002260 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002261 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002262 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002263 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002264 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002265
2266 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2267 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002268 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002269 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002270
Eli Friedman709b33d2009-07-13 22:27:52 +00002271 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002272 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002273 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002274 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002275 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002276
2277 if (isa<PHINode>(LHS))
2278 if (Instruction *NV = FoldOpIntoPhi(I))
2279 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002280
Chris Lattner4f637d42006-01-06 17:59:59 +00002281 ConstantInt *XorRHS = 0;
2282 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002283 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002284 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002285 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002286 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002287
Zhou Sheng4351c642007-04-02 08:20:41 +00002288 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002289 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2290 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002291 do {
2292 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002293 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2294 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002295 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2296 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002297 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002298 if (!MaskedValueIsZero(XorLHS,
2299 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002300 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002301 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002302 }
2303 }
2304 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002305 C0080Val = APIntOps::lshr(C0080Val, Size);
2306 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2307 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002308
Reid Spencer35c38852007-03-28 01:36:16 +00002309 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002310 // with funny bit widths then this switch statement should be removed. It
2311 // is just here to get the size of the "middle" type back up to something
2312 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002313 const Type *MiddleType = 0;
2314 switch (Size) {
2315 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002316 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2317 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2318 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002319 }
2320 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002321 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002322 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002323 }
2324 }
Chris Lattner66331a42004-04-10 22:01:55 +00002325 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002326
Owen Anderson1d0be152009-08-13 21:58:54 +00002327 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002328 return BinaryOperator::CreateXor(LHS, RHS);
2329
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002330 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002331 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002332 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002333 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002334
2335 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2336 if (RHSI->getOpcode() == Instruction::Sub)
2337 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2338 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2339 }
2340 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2341 if (LHSI->getOpcode() == Instruction::Sub)
2342 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2343 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2344 }
Robert Bocchino71698282004-07-27 21:02:21 +00002345 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002346
Chris Lattner5c4afb92002-05-08 22:46:53 +00002347 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002348 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002349 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002350 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002351 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002352 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002353 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002354 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002355 }
2356
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002357 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002358 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002359
2360 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002361 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002362 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002363 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002364
Misha Brukmanfd939082005-04-21 23:48:37 +00002365
Chris Lattner50af16a2004-11-13 19:50:12 +00002366 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002367 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002368 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002369 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002370
2371 // X*C1 + X*C2 --> X * (C1+C2)
2372 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002373 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002374 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002375 }
2376
2377 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002378 if (dyn_castFoldableMul(RHS, C2) == LHS)
2379 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002380
Chris Lattnere617c9e2007-01-05 02:17:46 +00002381 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002382 if (dyn_castNotVal(LHS) == RHS ||
2383 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002384 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002385
Chris Lattnerad3448c2003-02-18 19:57:07 +00002386
Chris Lattner564a7272003-08-13 19:01:45 +00002387 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002388 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2389 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002390 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002391
2392 // A+B --> A|B iff A and B have no bits set in common.
2393 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2394 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2395 APInt LHSKnownOne(IT->getBitWidth(), 0);
2396 APInt LHSKnownZero(IT->getBitWidth(), 0);
2397 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2398 if (LHSKnownZero != 0) {
2399 APInt RHSKnownOne(IT->getBitWidth(), 0);
2400 APInt RHSKnownZero(IT->getBitWidth(), 0);
2401 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2402
2403 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002404 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002405 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002406 }
2407 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002408
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002409 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002410 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002411 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002412 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2413 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002414 if (W != Y) {
2415 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002416 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002417 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002418 std::swap(W, X);
2419 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002420 std::swap(Y, Z);
2421 std::swap(W, X);
2422 }
2423 }
2424
2425 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002426 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002427 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002428 }
2429 }
2430 }
2431
Chris Lattner6b032052003-10-02 15:11:26 +00002432 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002433 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002434 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002435 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002436
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002437 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002438 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002439 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002440 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002441 if (Anded == CRHS) {
2442 // See if all bits from the first bit set in the Add RHS up are included
2443 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002444 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002445
2446 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002447 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002448
2449 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002450 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002451
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002452 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2453 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002454 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002455 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002456 }
2457 }
2458 }
2459
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002460 // Try to fold constant add into select arguments.
2461 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002462 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002463 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002464 }
2465
Chris Lattner42790482007-12-20 01:56:58 +00002466 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002467 {
2468 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002469 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002470 if (!SI) {
2471 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002472 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002473 }
Chris Lattner42790482007-12-20 01:56:58 +00002474 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002475 Value *TV = SI->getTrueValue();
2476 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002477 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002478
2479 // Can we fold the add into the argument of the select?
2480 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002481 if (match(FV, m_Zero()) &&
2482 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002483 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002484 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002485 if (match(TV, m_Zero()) &&
2486 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002487 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002488 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002489 }
2490 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002491
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002492 // Check for (add (sext x), y), see if we can merge this into an
2493 // integer add followed by a sext.
2494 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2495 // (add (sext x), cst) --> (sext (add x, cst'))
2496 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2497 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002498 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002499 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002500 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002501 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2502 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002503 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2504 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002505 return new SExtInst(NewAdd, I.getType());
2506 }
2507 }
2508
2509 // (add (sext x), (sext y)) --> (sext (add int x, y))
2510 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2511 // Only do this if x/y have the same type, if at last one of them has a
2512 // single use (so we don't increase the number of sexts), and if the
2513 // integer add will not overflow.
2514 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2515 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2516 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2517 RHSConv->getOperand(0))) {
2518 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002519 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2520 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002521 return new SExtInst(NewAdd, I.getType());
2522 }
2523 }
2524 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002525
2526 return Changed ? &I : 0;
2527}
2528
2529Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2530 bool Changed = SimplifyCommutative(I);
2531 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2532
2533 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2534 // X + 0 --> X
2535 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002536 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002537 (I.getType())->getValueAPF()))
2538 return ReplaceInstUsesWith(I, LHS);
2539 }
2540
2541 if (isa<PHINode>(LHS))
2542 if (Instruction *NV = FoldOpIntoPhi(I))
2543 return NV;
2544 }
2545
2546 // -A + B --> B - A
2547 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002548 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002549 return BinaryOperator::CreateFSub(RHS, LHSV);
2550
2551 // A + -B --> A - B
2552 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002553 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002554 return BinaryOperator::CreateFSub(LHS, V);
2555
2556 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2557 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2558 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2559 return ReplaceInstUsesWith(I, LHS);
2560
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002561 // Check for (add double (sitofp x), y), see if we can merge this into an
2562 // integer add followed by a promotion.
2563 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2564 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2565 // ... if the constant fits in the integer value. This is useful for things
2566 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2567 // requires a constant pool load, and generally allows the add to be better
2568 // instcombined.
2569 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2570 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002571 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002572 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002573 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002574 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2575 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002576 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2577 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002578 return new SIToFPInst(NewAdd, I.getType());
2579 }
2580 }
2581
2582 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2583 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2584 // Only do this if x/y have the same type, if at last one of them has a
2585 // single use (so we don't increase the number of int->fp conversions),
2586 // and if the integer add will not overflow.
2587 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2588 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2589 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2590 RHSConv->getOperand(0))) {
2591 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002592 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002593 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002594 return new SIToFPInst(NewAdd, I.getType());
2595 }
2596 }
2597 }
2598
Chris Lattner7e708292002-06-25 16:13:24 +00002599 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002600}
2601
Chris Lattner092543c2009-11-04 08:05:20 +00002602
2603/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2604/// code necessary to compute the offset from the base pointer (without adding
2605/// in the base pointer). Return the result as a signed integer of intptr size.
2606static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2607 TargetData &TD = *IC.getTargetData();
2608 gep_type_iterator GTI = gep_type_begin(GEP);
2609 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2610 Value *Result = Constant::getNullValue(IntPtrTy);
2611
2612 // Build a mask for high order bits.
2613 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2614 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2615
2616 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2617 ++i, ++GTI) {
2618 Value *Op = *i;
2619 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2620 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2621 if (OpC->isZero()) continue;
2622
2623 // Handle a struct index, which adds its field offset to the pointer.
2624 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2625 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2626
2627 Result = IC.Builder->CreateAdd(Result,
2628 ConstantInt::get(IntPtrTy, Size),
2629 GEP->getName()+".offs");
2630 continue;
2631 }
2632
2633 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2634 Constant *OC =
2635 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2636 Scale = ConstantExpr::getMul(OC, Scale);
2637 // Emit an add instruction.
2638 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2639 continue;
2640 }
2641 // Convert to correct type.
2642 if (Op->getType() != IntPtrTy)
2643 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2644 if (Size != 1) {
2645 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2646 // We'll let instcombine(mul) convert this to a shl if possible.
2647 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2648 }
2649
2650 // Emit an add instruction.
2651 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2652 }
2653 return Result;
2654}
2655
2656
2657/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2658/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2659/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2660/// be complex, and scales are involved. The above expression would also be
2661/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2662/// This later form is less amenable to optimization though, and we are allowed
2663/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2664///
2665/// If we can't emit an optimized form for this expression, this returns null.
2666///
2667static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2668 InstCombiner &IC) {
2669 TargetData &TD = *IC.getTargetData();
2670 gep_type_iterator GTI = gep_type_begin(GEP);
2671
2672 // Check to see if this gep only has a single variable index. If so, and if
2673 // any constant indices are a multiple of its scale, then we can compute this
2674 // in terms of the scale of the variable index. For example, if the GEP
2675 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2676 // because the expression will cross zero at the same point.
2677 unsigned i, e = GEP->getNumOperands();
2678 int64_t Offset = 0;
2679 for (i = 1; i != e; ++i, ++GTI) {
2680 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2681 // Compute the aggregate offset of constant indices.
2682 if (CI->isZero()) continue;
2683
2684 // Handle a struct index, which adds its field offset to the pointer.
2685 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2686 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2687 } else {
2688 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2689 Offset += Size*CI->getSExtValue();
2690 }
2691 } else {
2692 // Found our variable index.
2693 break;
2694 }
2695 }
2696
2697 // If there are no variable indices, we must have a constant offset, just
2698 // evaluate it the general way.
2699 if (i == e) return 0;
2700
2701 Value *VariableIdx = GEP->getOperand(i);
2702 // Determine the scale factor of the variable element. For example, this is
2703 // 4 if the variable index is into an array of i32.
2704 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2705
2706 // Verify that there are no other variable indices. If so, emit the hard way.
2707 for (++i, ++GTI; i != e; ++i, ++GTI) {
2708 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2709 if (!CI) return 0;
2710
2711 // Compute the aggregate offset of constant indices.
2712 if (CI->isZero()) continue;
2713
2714 // Handle a struct index, which adds its field offset to the pointer.
2715 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2716 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2717 } else {
2718 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2719 Offset += Size*CI->getSExtValue();
2720 }
2721 }
2722
2723 // Okay, we know we have a single variable index, which must be a
2724 // pointer/array/vector index. If there is no offset, life is simple, return
2725 // the index.
2726 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2727 if (Offset == 0) {
2728 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2729 // we don't need to bother extending: the extension won't affect where the
2730 // computation crosses zero.
2731 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2732 VariableIdx = new TruncInst(VariableIdx,
2733 TD.getIntPtrType(VariableIdx->getContext()),
2734 VariableIdx->getName(), &I);
2735 return VariableIdx;
2736 }
2737
2738 // Otherwise, there is an index. The computation we will do will be modulo
2739 // the pointer size, so get it.
2740 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2741
2742 Offset &= PtrSizeMask;
2743 VariableScale &= PtrSizeMask;
2744
2745 // To do this transformation, any constant index must be a multiple of the
2746 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2747 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2748 // multiple of the variable scale.
2749 int64_t NewOffs = Offset / (int64_t)VariableScale;
2750 if (Offset != NewOffs*(int64_t)VariableScale)
2751 return 0;
2752
2753 // Okay, we can do this evaluation. Start by converting the index to intptr.
2754 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2755 if (VariableIdx->getType() != IntPtrTy)
2756 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2757 true /*SExt*/,
2758 VariableIdx->getName(), &I);
2759 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2760 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2761}
2762
2763
2764/// Optimize pointer differences into the same array into a size. Consider:
2765/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2766/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2767///
2768Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2769 const Type *Ty) {
2770 assert(TD && "Must have target data info for this");
2771
2772 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2773 // this.
2774 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00002775 GetElementPtrInst *GEP = 0;
2776 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00002777
Chris Lattner85c1c962010-01-01 22:42:29 +00002778 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2779 // For now we require one side to be the base pointer "A" or a constant
2780 // expression derived from it.
2781 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2782 // (gep X, ...) - X
2783 if (LHSGEP->getOperand(0) == RHS) {
2784 GEP = LHSGEP;
2785 Swapped = false;
2786 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2787 // (gep X, ...) - (ce_gep X, ...)
2788 if (CE->getOpcode() == Instruction::GetElementPtr &&
2789 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2790 CstGEP = CE;
2791 GEP = LHSGEP;
2792 Swapped = false;
2793 }
2794 }
2795 }
2796
2797 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2798 // X - (gep X, ...)
2799 if (RHSGEP->getOperand(0) == LHS) {
2800 GEP = RHSGEP;
2801 Swapped = true;
2802 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2803 // (ce_gep X, ...) - (gep X, ...)
2804 if (CE->getOpcode() == Instruction::GetElementPtr &&
2805 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2806 CstGEP = CE;
2807 GEP = RHSGEP;
2808 Swapped = true;
2809 }
2810 }
2811 }
2812
2813 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00002814 return 0;
2815
Chris Lattner092543c2009-11-04 08:05:20 +00002816 // Emit the offset of the GEP and an intptr_t.
2817 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00002818
2819 // If we had a constant expression GEP on the other side offsetting the
2820 // pointer, subtract it from the offset we have.
2821 if (CstGEP) {
2822 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2823 Result = Builder->CreateSub(Result, CstOffset);
2824 }
2825
Chris Lattner092543c2009-11-04 08:05:20 +00002826
2827 // If we have p - gep(p, ...) then we have to negate the result.
2828 if (Swapped)
2829 Result = Builder->CreateNeg(Result, "diff.neg");
2830
2831 return Builder->CreateIntCast(Result, Ty, true);
2832}
2833
2834
Chris Lattner7e708292002-06-25 16:13:24 +00002835Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002836 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002837
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002838 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002840
Chris Lattner3bf68152009-12-21 04:04:05 +00002841 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2842 if (Value *V = dyn_castNegVal(Op1)) {
2843 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2844 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2845 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2846 return Res;
2847 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002848
Chris Lattnere87597f2004-10-16 18:11:37 +00002849 if (isa<UndefValue>(Op0))
2850 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2851 if (isa<UndefValue>(Op1))
2852 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002853 if (I.getType() == Type::getInt1Ty(*Context))
2854 return BinaryOperator::CreateXor(Op0, Op1);
2855
Chris Lattnerd65460f2003-11-05 01:06:05 +00002856 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002857 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002858 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002859 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002860
Chris Lattnerd65460f2003-11-05 01:06:05 +00002861 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002862 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002863 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002864 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002865
Chris Lattner76b7a062007-01-15 07:02:54 +00002866 // -(X >>u 31) -> (X >>s 31)
2867 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002868 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002869 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002870 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002871 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002872 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002873 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002874 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002875 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002876 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002877 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002878 }
2879 }
Chris Lattner092543c2009-11-04 08:05:20 +00002880 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002881 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2882 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002883 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002884 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002885 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002886 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002887 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002888 }
2889 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002890 }
2891 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002892 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002893
2894 // Try to fold constant sub into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002897 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002898
2899 // C - zext(bool) -> bool ? C - 1 : C
2900 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002901 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002902 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002903 }
2904
Chris Lattner43d84d62005-04-07 16:15:25 +00002905 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002906 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002907 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002908 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002909 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002910 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002911 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002912 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002913 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2914 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2915 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002916 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002917 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002918 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002919 }
2920
Chris Lattnerfd059242003-10-15 16:48:29 +00002921 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002922 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2923 // is not used by anyone else...
2924 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002925 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002926 // Swap the two operands of the subexpr...
2927 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2928 Op1I->setOperand(0, IIOp1);
2929 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002930
Chris Lattnera2881962003-02-18 19:28:33 +00002931 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002932 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002933 }
2934
2935 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2936 //
2937 if (Op1I->getOpcode() == Instruction::And &&
2938 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2939 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2940
Chris Lattner74381062009-08-30 07:44:24 +00002941 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002942 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002943 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002944
Reid Spencerac5209e2006-10-16 23:08:08 +00002945 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002946 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002947 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002948 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002949 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002950 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002951 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002952
Chris Lattnerad3448c2003-02-18 19:57:07 +00002953 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002954 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002955 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002956 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002957 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002958 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002959 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002960 }
Chris Lattner40371712002-05-09 01:29:19 +00002961 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002962 }
Chris Lattnera2881962003-02-18 19:28:33 +00002963
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002964 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2965 if (Op0I->getOpcode() == Instruction::Add) {
2966 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2967 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2968 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2969 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2970 } else if (Op0I->getOpcode() == Instruction::Sub) {
2971 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002972 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002973 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002974 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002975 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002976
Chris Lattner50af16a2004-11-13 19:50:12 +00002977 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002978 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002979 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002980 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002981
Chris Lattner50af16a2004-11-13 19:50:12 +00002982 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002983 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002984 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002985 }
Chris Lattner092543c2009-11-04 08:05:20 +00002986
2987 // Optimize pointer differences into the same array into a size. Consider:
2988 // &A[10] - &A[0]: we should compile this to "10".
2989 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002990 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002991 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2992 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00002993 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2994 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002995
2996 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002997 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2998 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2999 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
3000 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00003001 }
3002
Chris Lattner3f5b8772002-05-06 16:14:14 +00003003 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003004}
3005
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003006Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3008
3009 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00003010 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003011 return BinaryOperator::CreateFAdd(Op0, V);
3012
3013 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3014 if (Op1I->getOpcode() == Instruction::FAdd) {
3015 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00003016 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00003017 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003018 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00003019 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00003020 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003021 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003022 }
3023
3024 return 0;
3025}
3026
Chris Lattnera0141b92007-07-15 20:42:37 +00003027/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3028/// comparison only checks the sign bit. If it only checks the sign bit, set
3029/// TrueIfSigned if the result of the comparison is true when the input value is
3030/// signed.
3031static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3032 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003033 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003034 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3035 TrueIfSigned = true;
3036 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003037 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3038 TrueIfSigned = true;
3039 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003040 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3041 TrueIfSigned = false;
3042 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003043 case ICmpInst::ICMP_UGT:
3044 // True if LHS u> RHS and RHS == high-bit-mask - 1
3045 TrueIfSigned = true;
3046 return RHS->getValue() ==
3047 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3048 case ICmpInst::ICMP_UGE:
3049 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3050 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00003051 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00003052 default:
3053 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003054 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003055}
3056
Chris Lattner7e708292002-06-25 16:13:24 +00003057Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003058 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003060
Chris Lattnera2498472009-10-11 21:36:10 +00003061 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003063
Chris Lattner8af304a2009-10-11 07:53:15 +00003064 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00003065 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3066 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003067
3068 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003069 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003070 if (SI->getOpcode() == Instruction::Shl)
3071 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003072 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003073 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003074
Zhou Sheng843f07672007-04-19 05:39:12 +00003075 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00003076 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00003077 if (CI->equalsInt(1)) // X * 1 == X
3078 return ReplaceInstUsesWith(I, Op0);
3079 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003080 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003081
Zhou Sheng97b52c22007-03-29 01:57:21 +00003082 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003083 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003084 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003085 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003086 }
Chris Lattnera2498472009-10-11 21:36:10 +00003087 } else if (isa<VectorType>(Op1C->getType())) {
3088 if (Op1C->isNullValue())
3089 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003090
Chris Lattnera2498472009-10-11 21:36:10 +00003091 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003092 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003093 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003094
3095 // As above, vector X*splat(1.0) -> X in all defined cases.
3096 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003097 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3098 if (CI->equalsInt(1))
3099 return ReplaceInstUsesWith(I, Op0);
3100 }
3101 }
Chris Lattnera2881962003-02-18 19:28:33 +00003102 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003103
3104 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3105 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003106 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003107 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003108 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3109 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003110 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003111
3112 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003113
3114 // Try to fold constant mul into select arguments.
3115 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003116 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003117 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003118
3119 if (isa<PHINode>(Op0))
3120 if (Instruction *NV = FoldOpIntoPhi(I))
3121 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003122 }
3123
Dan Gohman186a6362009-08-12 16:04:34 +00003124 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003125 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003126 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003127
Nick Lewycky0c730792008-11-21 07:33:58 +00003128 // (X / Y) * Y = X - (X % Y)
3129 // (X / Y) * -Y = (X % Y) - X
3130 {
Chris Lattnera2498472009-10-11 21:36:10 +00003131 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003132 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3133 if (!BO ||
3134 (BO->getOpcode() != Instruction::UDiv &&
3135 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003136 Op1C = Op0;
3137 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003138 }
Chris Lattnera2498472009-10-11 21:36:10 +00003139 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003140 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003141 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003142 (BO->getOpcode() == Instruction::UDiv ||
3143 BO->getOpcode() == Instruction::SDiv)) {
3144 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3145
Dan Gohmanfa94b942009-08-12 16:33:09 +00003146 // If the division is exact, X % Y is zero.
3147 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3148 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003149 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003150 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003151 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003152 }
3153
Chris Lattner74381062009-08-30 07:44:24 +00003154 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003155 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003156 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003157 else
Chris Lattner74381062009-08-30 07:44:24 +00003158 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003159 Rem->takeName(BO);
3160
Chris Lattnera2498472009-10-11 21:36:10 +00003161 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003162 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003163 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003164 }
3165 }
3166
Chris Lattner8af304a2009-10-11 07:53:15 +00003167 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003168 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003169 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003170
Chris Lattner8af304a2009-10-11 07:53:15 +00003171 // X*(1 << Y) --> X << Y
3172 // (1 << Y)*X --> X << Y
3173 {
3174 Value *Y;
3175 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003176 return BinaryOperator::CreateShl(Op1, Y);
3177 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003178 return BinaryOperator::CreateShl(Op0, Y);
3179 }
3180
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003181 // If one of the operands of the multiply is a cast from a boolean value, then
3182 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003183 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3184 if (!isa<VectorType>(I.getType())) {
3185 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003186 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003187
Chris Lattnerd2c58362009-10-11 21:29:45 +00003188 Value *BoolCast = 0, *OtherOp = 0;
3189 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003190 BoolCast = Op0, OtherOp = Op1;
3191 else if (MaskedValueIsZero(Op1, Negative2))
3192 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003193
Chris Lattner0036e3a2009-10-11 21:22:21 +00003194 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003195 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3196 BoolCast, "tmp");
3197 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003198 }
3199 }
3200
Chris Lattner7e708292002-06-25 16:13:24 +00003201 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003202}
3203
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003204Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3205 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003206 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003207
3208 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003209 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3210 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003211 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3212 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3213 if (Op1F->isExactlyValue(1.0))
3214 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003215 } else if (isa<VectorType>(Op1C->getType())) {
3216 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003217 // As above, vector X*splat(1.0) -> X in all defined cases.
3218 if (Constant *Splat = Op1V->getSplatValue()) {
3219 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3220 if (F->isExactlyValue(1.0))
3221 return ReplaceInstUsesWith(I, Op0);
3222 }
3223 }
3224 }
3225
3226 // Try to fold constant mul into select arguments.
3227 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3228 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3229 return R;
3230
3231 if (isa<PHINode>(Op0))
3232 if (Instruction *NV = FoldOpIntoPhi(I))
3233 return NV;
3234 }
3235
Dan Gohman186a6362009-08-12 16:04:34 +00003236 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003237 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003238 return BinaryOperator::CreateFMul(Op0v, Op1v);
3239
3240 return Changed ? &I : 0;
3241}
3242
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003243/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3244/// instruction.
3245bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3246 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3247
3248 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3249 int NonNullOperand = -1;
3250 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3251 if (ST->isNullValue())
3252 NonNullOperand = 2;
3253 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3254 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3255 if (ST->isNullValue())
3256 NonNullOperand = 1;
3257
3258 if (NonNullOperand == -1)
3259 return false;
3260
3261 Value *SelectCond = SI->getOperand(0);
3262
3263 // Change the div/rem to use 'Y' instead of the select.
3264 I.setOperand(1, SI->getOperand(NonNullOperand));
3265
3266 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3267 // problem. However, the select, or the condition of the select may have
3268 // multiple uses. Based on our knowledge that the operand must be non-zero,
3269 // propagate the known value for the select into other uses of it, and
3270 // propagate a known value of the condition into its other users.
3271
3272 // If the select and condition only have a single use, don't bother with this,
3273 // early exit.
3274 if (SI->use_empty() && SelectCond->hasOneUse())
3275 return true;
3276
3277 // Scan the current block backward, looking for other uses of SI.
3278 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3279
3280 while (BBI != BBFront) {
3281 --BBI;
3282 // If we found a call to a function, we can't assume it will return, so
3283 // information from below it cannot be propagated above it.
3284 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3285 break;
3286
3287 // Replace uses of the select or its condition with the known values.
3288 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3289 I != E; ++I) {
3290 if (*I == SI) {
3291 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003292 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003293 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003294 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3295 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003296 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003297 }
3298 }
3299
3300 // If we past the instruction, quit looking for it.
3301 if (&*BBI == SI)
3302 SI = 0;
3303 if (&*BBI == SelectCond)
3304 SelectCond = 0;
3305
3306 // If we ran out of things to eliminate, break out of the loop.
3307 if (SelectCond == 0 && SI == 0)
3308 break;
3309
3310 }
3311 return true;
3312}
3313
3314
Reid Spencer1628cec2006-10-26 06:15:43 +00003315/// This function implements the transforms on div instructions that work
3316/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3317/// used by the visitors to those instructions.
3318/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003319Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003320 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003321
Chris Lattner50b2ca42008-02-19 06:12:18 +00003322 // undef / X -> 0 for integer.
3323 // undef / X -> undef for FP (the undef could be a snan).
3324 if (isa<UndefValue>(Op0)) {
3325 if (Op0->getType()->isFPOrFPVector())
3326 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003327 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003328 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003329
3330 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003331 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003332 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003333
Reid Spencer1628cec2006-10-26 06:15:43 +00003334 return 0;
3335}
Misha Brukmanfd939082005-04-21 23:48:37 +00003336
Reid Spencer1628cec2006-10-26 06:15:43 +00003337/// This function implements the transforms common to both integer division
3338/// instructions (udiv and sdiv). It is called by the visitors to those integer
3339/// division instructions.
3340/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003341Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003342 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3343
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003344 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003345 if (Op0 == Op1) {
3346 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003347 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003348 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003349 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003350 }
3351
Owen Andersoneed707b2009-07-24 23:12:02 +00003352 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003353 return ReplaceInstUsesWith(I, CI);
3354 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003355
Reid Spencer1628cec2006-10-26 06:15:43 +00003356 if (Instruction *Common = commonDivTransforms(I))
3357 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003358
3359 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3360 // This does not apply for fdiv.
3361 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3362 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003363
3364 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3365 // div X, 1 == X
3366 if (RHS->equalsInt(1))
3367 return ReplaceInstUsesWith(I, Op0);
3368
3369 // (X / C1) / C2 -> X / (C1*C2)
3370 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3371 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3372 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003373 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003374 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003375 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003376 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003377 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003378 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003379 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003380
Reid Spencerbca0e382007-03-23 20:05:17 +00003381 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3383 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3384 return R;
3385 if (isa<PHINode>(Op0))
3386 if (Instruction *NV = FoldOpIntoPhi(I))
3387 return NV;
3388 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003389 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003390
Chris Lattnera2881962003-02-18 19:28:33 +00003391 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003392 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003393 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003394 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003395
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003396 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003397 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003398 return ReplaceInstUsesWith(I, Op0);
3399
Nick Lewycky895f0852008-11-27 20:21:08 +00003400 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3401 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3402 // div X, 1 == X
3403 if (X->isOne())
3404 return ReplaceInstUsesWith(I, Op0);
3405 }
3406
Reid Spencer1628cec2006-10-26 06:15:43 +00003407 return 0;
3408}
3409
3410Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3412
3413 // Handle the integer div common cases
3414 if (Instruction *Common = commonIDivTransforms(I))
3415 return Common;
3416
Reid Spencer1628cec2006-10-26 06:15:43 +00003417 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003418 // X udiv C^2 -> X >> C
3419 // Check to see if this is an unsigned division with an exact power of 2,
3420 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003421 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003422 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003423 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003424
3425 // X udiv C, where C >= signbit
3426 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003427 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003428 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003429 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003430 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003431 }
3432
3433 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003434 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003435 if (RHSI->getOpcode() == Instruction::Shl &&
3436 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003437 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003438 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003439 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003440 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003441 if (uint32_t C2 = C1.logBase2())
3442 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003443 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003444 }
3445 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003446 }
3447
Reid Spencer1628cec2006-10-26 06:15:43 +00003448 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3449 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003450 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003451 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003452 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003453 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003454 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003455 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003456 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003457 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003458 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003459 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003460
3461 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003462 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003463 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003464
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003465 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003466 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003467 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003468 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003469 return 0;
3470}
3471
Reid Spencer1628cec2006-10-26 06:15:43 +00003472Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3473 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3474
3475 // Handle the integer div common cases
3476 if (Instruction *Common = commonIDivTransforms(I))
3477 return Common;
3478
3479 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3480 // sdiv X, -1 == -X
3481 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003482 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003483
Dan Gohmanfa94b942009-08-12 16:33:09 +00003484 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003485 if (cast<SDivOperator>(&I)->isExact() &&
3486 RHS->getValue().isNonNegative() &&
3487 RHS->getValue().isPowerOf2()) {
3488 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3489 RHS->getValue().exactLogBase2());
3490 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3491 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003492
3493 // -X/C --> X/-C provided the negation doesn't overflow.
3494 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3495 if (isa<Constant>(Sub->getOperand(0)) &&
3496 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003497 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003498 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3499 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003500 }
3501
3502 // If the sign bits of both operands are zero (i.e. we can prove they are
3503 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003504 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003505 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003506 if (MaskedValueIsZero(Op0, Mask)) {
3507 if (MaskedValueIsZero(Op1, Mask)) {
3508 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3509 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3510 }
3511 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003512 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003513 ShiftedInt->getValue().isPowerOf2()) {
3514 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3515 // Safe because the only negative value (1 << Y) can take on is
3516 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3517 // the sign bit set.
3518 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3519 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003520 }
Eli Friedman8be17392009-07-18 09:53:21 +00003521 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003522
3523 return 0;
3524}
3525
3526Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3527 return commonDivTransforms(I);
3528}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003529
Reid Spencer0a783f72006-11-02 01:53:59 +00003530/// This function implements the transforms on rem instructions that work
3531/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3532/// is used by the visitors to those instructions.
3533/// @brief Transforms common to all three rem instructions
3534Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003535 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003536
Chris Lattner50b2ca42008-02-19 06:12:18 +00003537 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3538 if (I.getType()->isFPOrFPVector())
3539 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003540 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003541 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003542 if (isa<UndefValue>(Op1))
3543 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003544
3545 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003546 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3547 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003548
Reid Spencer0a783f72006-11-02 01:53:59 +00003549 return 0;
3550}
3551
3552/// This function implements the transforms common to both integer remainder
3553/// instructions (urem and srem). It is called by the visitors to those integer
3554/// remainder instructions.
3555/// @brief Common integer remainder transforms
3556Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3558
3559 if (Instruction *common = commonRemTransforms(I))
3560 return common;
3561
Dale Johannesened6af242009-01-21 00:35:19 +00003562 // 0 % X == 0 for integer, we don't need to preserve faults!
3563 if (Constant *LHS = dyn_cast<Constant>(Op0))
3564 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003565 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003566
Chris Lattner857e8cd2004-12-12 21:48:58 +00003567 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003568 // X % 0 == undef, we don't need to preserve faults!
3569 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003570 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003571
Chris Lattnera2881962003-02-18 19:28:33 +00003572 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003573 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003574
Chris Lattner97943922006-02-28 05:49:21 +00003575 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3576 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3577 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3578 return R;
3579 } else if (isa<PHINode>(Op0I)) {
3580 if (Instruction *NV = FoldOpIntoPhi(I))
3581 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003582 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003583
3584 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003585 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003586 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003587 }
Chris Lattnera2881962003-02-18 19:28:33 +00003588 }
3589
Reid Spencer0a783f72006-11-02 01:53:59 +00003590 return 0;
3591}
3592
3593Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3594 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3595
3596 if (Instruction *common = commonIRemTransforms(I))
3597 return common;
3598
3599 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3600 // X urem C^2 -> X and C
3601 // Check to see if this is an unsigned remainder with an exact power of 2,
3602 // if so, convert to a bitwise and.
3603 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003604 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003605 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003606 }
3607
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003608 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003609 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3610 if (RHSI->getOpcode() == Instruction::Shl &&
3611 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003612 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003613 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003614 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003615 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003616 }
3617 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003618 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003619
Reid Spencer0a783f72006-11-02 01:53:59 +00003620 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3621 // where C1&C2 are powers of two.
3622 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3623 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3624 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3625 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003626 if ((STO->getValue().isPowerOf2()) &&
3627 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003628 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3629 SI->getName()+".t");
3630 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3631 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003632 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003633 }
3634 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003635 }
3636
Chris Lattner3f5b8772002-05-06 16:14:14 +00003637 return 0;
3638}
3639
Reid Spencer0a783f72006-11-02 01:53:59 +00003640Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3641 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3642
Dan Gohmancff55092007-11-05 23:16:33 +00003643 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003644 if (Instruction *Common = commonIRemTransforms(I))
3645 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003646
Dan Gohman186a6362009-08-12 16:04:34 +00003647 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003648 if (!isa<Constant>(RHSNeg) ||
3649 (isa<ConstantInt>(RHSNeg) &&
3650 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003651 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003652 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003653 I.setOperand(1, RHSNeg);
3654 return &I;
3655 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003656
Dan Gohmancff55092007-11-05 23:16:33 +00003657 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003658 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003659 if (I.getType()->isInteger()) {
3660 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3661 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3662 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003663 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003664 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003665 }
3666
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003667 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003668 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3669 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003670
Nick Lewycky9dce8732008-12-20 16:48:00 +00003671 bool hasNegative = false;
3672 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3673 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3674 if (RHS->getValue().isNegative())
3675 hasNegative = true;
3676
3677 if (hasNegative) {
3678 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003679 for (unsigned i = 0; i != VWidth; ++i) {
3680 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3681 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003682 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003683 else
3684 Elts[i] = RHS;
3685 }
3686 }
3687
Owen Andersonaf7ec972009-07-28 21:19:26 +00003688 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003689 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003690 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003691 I.setOperand(1, NewRHSV);
3692 return &I;
3693 }
3694 }
3695 }
3696
Reid Spencer0a783f72006-11-02 01:53:59 +00003697 return 0;
3698}
3699
3700Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003701 return commonRemTransforms(I);
3702}
3703
Chris Lattner457dd822004-06-09 07:59:58 +00003704// isOneBitSet - Return true if there is exactly one bit set in the specified
3705// constant.
3706static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003707 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003708}
3709
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003710// isHighOnes - Return true if the constant is of the form 1+0+.
3711// This is the same as lowones(~X).
3712static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003713 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003714}
3715
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003717/// are carefully arranged to allow folding of expressions such as:
3718///
3719/// (A < B) | (A > B) --> (A != B)
3720///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003721/// Note that this is only valid if the first and second predicates have the
3722/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003723///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003724/// Three bits are used to represent the condition, as follows:
3725/// 0 A > B
3726/// 1 A == B
3727/// 2 A < B
3728///
3729/// <=> Value Definition
3730/// 000 0 Always false
3731/// 001 1 A > B
3732/// 010 2 A == B
3733/// 011 3 A >= B
3734/// 100 4 A < B
3735/// 101 5 A != B
3736/// 110 6 A <= B
3737/// 111 7 Always true
3738///
3739static unsigned getICmpCode(const ICmpInst *ICI) {
3740 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003741 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003742 case ICmpInst::ICMP_UGT: return 1; // 001
3743 case ICmpInst::ICMP_SGT: return 1; // 001
3744 case ICmpInst::ICMP_EQ: return 2; // 010
3745 case ICmpInst::ICMP_UGE: return 3; // 011
3746 case ICmpInst::ICMP_SGE: return 3; // 011
3747 case ICmpInst::ICMP_ULT: return 4; // 100
3748 case ICmpInst::ICMP_SLT: return 4; // 100
3749 case ICmpInst::ICMP_NE: return 5; // 101
3750 case ICmpInst::ICMP_ULE: return 6; // 110
3751 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003752 // True -> 7
3753 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003754 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003755 return 0;
3756 }
3757}
3758
Evan Cheng8db90722008-10-14 17:15:11 +00003759/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3760/// predicate into a three bit mask. It also returns whether it is an ordered
3761/// predicate by reference.
3762static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3763 isOrdered = false;
3764 switch (CC) {
3765 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3766 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003767 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3768 case FCmpInst::FCMP_UGT: return 1; // 001
3769 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3770 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003771 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3772 case FCmpInst::FCMP_UGE: return 3; // 011
3773 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3774 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003775 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3776 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003777 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3778 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003779 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003780 default:
3781 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003782 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003783 return 0;
3784 }
3785}
3786
Reid Spencere4d87aa2006-12-23 06:05:41 +00003787/// getICmpValue - This is the complement of getICmpCode, which turns an
3788/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003789/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003790/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003791static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003792 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003793 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003794 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003795 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003796 case 1:
3797 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003798 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003799 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003800 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3801 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003802 case 3:
3803 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003804 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003805 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003806 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003807 case 4:
3808 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003809 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003810 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003811 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3812 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003813 case 6:
3814 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003815 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003816 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003817 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003818 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003819 }
3820}
3821
Evan Cheng8db90722008-10-14 17:15:11 +00003822/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3823/// opcode and two operands into either a FCmp instruction. isordered is passed
3824/// in to determine which kind of predicate to use in the new fcmp instruction.
3825static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003826 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003827 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003828 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003829 case 0:
3830 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003831 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003832 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003833 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003834 case 1:
3835 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003836 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003837 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003838 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003839 case 2:
3840 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003841 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003842 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003843 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003844 case 3:
3845 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003846 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003847 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003848 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003849 case 4:
3850 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003851 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003852 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003853 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003854 case 5:
3855 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003856 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003857 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003858 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003859 case 6:
3860 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003861 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003862 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003863 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003864 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003865 }
3866}
3867
Chris Lattnerb9553d62008-11-16 04:55:20 +00003868/// PredicatesFoldable - Return true if both predicates match sign or if at
3869/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003870static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003871 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3872 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3873 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003874}
3875
3876namespace {
3877// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3878struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003879 InstCombiner &IC;
3880 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003881 ICmpInst::Predicate pred;
3882 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3883 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3884 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003885 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003886 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3887 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003888 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3889 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003890 return false;
3891 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003892 Instruction *apply(Instruction &Log) const {
3893 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3894 if (ICI->getOperand(0) != LHS) {
3895 assert(ICI->getOperand(1) == LHS);
3896 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003897 }
3898
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003899 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003900 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003901 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003902 unsigned Code;
3903 switch (Log.getOpcode()) {
3904 case Instruction::And: Code = LHSCode & RHSCode; break;
3905 case Instruction::Or: Code = LHSCode | RHSCode; break;
3906 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003907 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003908 }
3909
Nick Lewycky4a134af2009-10-25 05:20:17 +00003910 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003911 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003912 if (Instruction *I = dyn_cast<Instruction>(RV))
3913 return I;
3914 // Otherwise, it's a constant boolean value...
3915 return IC.ReplaceInstUsesWith(Log, RV);
3916 }
3917};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003918} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003919
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003920// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3921// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003922// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003923Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003924 ConstantInt *OpRHS,
3925 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003926 BinaryOperator &TheAnd) {
3927 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003928 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003929 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003930 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003931
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003932 switch (Op->getOpcode()) {
3933 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003934 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003935 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003936 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003937 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003938 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003939 }
3940 break;
3941 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003942 if (Together == AndRHS) // (X | C) & C --> C
3943 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003944
Chris Lattner6e7ba452005-01-01 16:22:27 +00003945 if (Op->hasOneUse() && Together != OpRHS) {
3946 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003947 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003948 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003949 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003950 }
3951 break;
3952 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003953 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003954 // Adding a one to a single bit bit-field should be turned into an XOR
3955 // of the bit. First thing to check is to see if this AND is with a
3956 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003957 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003958
3959 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003960 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003961 // Ok, at this point, we know that we are masking the result of the
3962 // ADD down to exactly one bit. If the constant we are adding has
3963 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003964 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003965
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003966 // Check to see if any bits below the one bit set in AndRHSV are set.
3967 if ((AddRHS & (AndRHSV-1)) == 0) {
3968 // If not, the only thing that can effect the output of the AND is
3969 // the bit specified by AndRHSV. If that bit is set, the effect of
3970 // the XOR is to toggle the bit. If it is clear, then the ADD has
3971 // no effect.
3972 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3973 TheAnd.setOperand(0, X);
3974 return &TheAnd;
3975 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003976 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003977 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003978 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003979 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003980 }
3981 }
3982 }
3983 }
3984 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003985
3986 case Instruction::Shl: {
3987 // We know that the AND will not produce any of the bits shifted in, so if
3988 // the anded constant includes them, clear them now!
3989 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003990 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003991 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003992 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003993 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003994
Zhou Sheng290bec52007-03-29 08:15:12 +00003995 if (CI->getValue() == ShlMask) {
3996 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003997 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3998 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003999 TheAnd.setOperand(1, CI);
4000 return &TheAnd;
4001 }
4002 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00004003 }
Reid Spencer3822ff52006-11-08 06:47:33 +00004004 case Instruction::LShr:
4005 {
Chris Lattner62a355c2003-09-19 19:05:02 +00004006 // We know that the AND will not produce any of the bits shifted in, so if
4007 // the anded constant includes them, clear them now! This only applies to
4008 // unsigned shifts, because a signed shr may bring in set bits!
4009 //
Zhou Sheng290bec52007-03-29 08:15:12 +00004010 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004011 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00004012 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00004013 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00004014
Zhou Sheng290bec52007-03-29 08:15:12 +00004015 if (CI->getValue() == ShrMask) {
4016 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00004017 return ReplaceInstUsesWith(TheAnd, Op);
4018 } else if (CI != AndRHS) {
4019 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
4020 return &TheAnd;
4021 }
4022 break;
4023 }
4024 case Instruction::AShr:
4025 // Signed shr.
4026 // See if this is shifting in some sign extension, then masking it out
4027 // with an and.
4028 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00004029 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004030 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00004031 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00004032 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00004033 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00004034 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00004035 // Make the argument unsigned.
4036 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00004037 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004038 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00004039 }
Chris Lattner62a355c2003-09-19 19:05:02 +00004040 }
4041 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004042 }
4043 return 0;
4044}
4045
Chris Lattner8b170942002-08-09 23:47:40 +00004046
Chris Lattnera96879a2004-09-29 17:40:11 +00004047/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4048/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00004049/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4050/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00004051/// insert new instructions.
4052Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004053 bool isSigned, bool Inside,
4054 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004055 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00004056 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00004057 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004058
Chris Lattnera96879a2004-09-29 17:40:11 +00004059 if (Inside) {
4060 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004061 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00004062
Reid Spencere4d87aa2006-12-23 06:05:41 +00004063 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004064 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00004065 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00004066 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004067 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004068 }
4069
4070 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00004071 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00004072 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004073 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004074 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004075 }
4076
4077 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004078 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00004079
Reid Spencere4e40032007-03-21 23:19:50 +00004080 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00004081 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004082 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004083 ICmpInst::Predicate pred = (isSigned ?
4084 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004085 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004086 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004087
Reid Spencere4e40032007-03-21 23:19:50 +00004088 // Emit V-Lo >u Hi-1-Lo
4089 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004090 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004091 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004092 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004093 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004094}
4095
Chris Lattner7203e152005-09-18 07:22:02 +00004096// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4097// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4098// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4099// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004100static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004101 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004102 uint32_t BitWidth = Val->getType()->getBitWidth();
4103 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004104
4105 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004106 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004107 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004108 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004109 return true;
4110}
4111
Chris Lattner7203e152005-09-18 07:22:02 +00004112/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4113/// where isSub determines whether the operator is a sub. If we can fold one of
4114/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004115///
4116/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4117/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4118/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4119///
4120/// return (A +/- B).
4121///
4122Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004123 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004124 Instruction &I) {
4125 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4126 if (!LHSI || LHSI->getNumOperands() != 2 ||
4127 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4128
4129 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4130
4131 switch (LHSI->getOpcode()) {
4132 default: return 0;
4133 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004134 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004135 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004136 if ((Mask->getValue().countLeadingZeros() +
4137 Mask->getValue().countPopulation()) ==
4138 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004139 break;
4140
4141 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4142 // part, we don't need any explicit masks to take them out of A. If that
4143 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004144 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004145 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004146 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004147 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004148 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004149 break;
4150 }
4151 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004152 return 0;
4153 case Instruction::Or:
4154 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004155 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004156 if ((Mask->getValue().countLeadingZeros() +
4157 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004158 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004159 break;
4160 return 0;
4161 }
4162
Chris Lattnerc8e77562005-09-18 04:24:45 +00004163 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004164 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4165 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004166}
4167
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004168/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4169Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4170 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004171 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004172 ConstantInt *LHSCst, *RHSCst;
4173 ICmpInst::Predicate LHSCC, RHSCC;
4174
Chris Lattnerea065fb2008-11-16 05:10:52 +00004175 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004176 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004177 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004178 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004179 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004180 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004181
Chris Lattner3f40e232009-11-29 00:51:17 +00004182 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4183 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4184 // where C is a power of 2
4185 if (LHSCC == ICmpInst::ICMP_ULT &&
4186 LHSCst->getValue().isPowerOf2()) {
4187 Value *NewOr = Builder->CreateOr(Val, Val2);
4188 return new ICmpInst(LHSCC, NewOr, LHSCst);
4189 }
4190
4191 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4192 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4193 Value *NewOr = Builder->CreateOr(Val, Val2);
4194 return new ICmpInst(LHSCC, NewOr, LHSCst);
4195 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004196 }
4197
4198 // From here on, we only handle:
4199 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4200 if (Val != Val2) return 0;
4201
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004202 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4203 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4204 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4205 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4206 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4207 return 0;
4208
4209 // We can't fold (ugt x, C) & (sgt x, C2).
4210 if (!PredicatesFoldable(LHSCC, RHSCC))
4211 return 0;
4212
4213 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004214 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004215 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004216 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004217 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004218 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004219 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004220 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4221
4222 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004223 std::swap(LHS, RHS);
4224 std::swap(LHSCst, RHSCst);
4225 std::swap(LHSCC, RHSCC);
4226 }
4227
4228 // At this point, we know we have have two icmp instructions
4229 // comparing a value against two constants and and'ing the result
4230 // together. Because of the above check, we know that we only have
4231 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4232 // (from the FoldICmpLogical check above), that the two constants
4233 // are not equal and that the larger constant is on the RHS
4234 assert(LHSCst != RHSCst && "Compares not folded above?");
4235
4236 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004237 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004238 case ICmpInst::ICMP_EQ:
4239 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004240 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004241 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4242 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4243 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004244 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004245 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4246 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4247 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4248 return ReplaceInstUsesWith(I, LHS);
4249 }
4250 case ICmpInst::ICMP_NE:
4251 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004252 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004253 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004254 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004255 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004256 break; // (X != 13 & X u< 15) -> no change
4257 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004258 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004259 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004260 break; // (X != 13 & X s< 15) -> no change
4261 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4262 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4263 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4264 return ReplaceInstUsesWith(I, RHS);
4265 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004266 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004267 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004268 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004269 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004270 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004271 }
4272 break; // (X != 13 & X != 15) -> no change
4273 }
4274 break;
4275 case ICmpInst::ICMP_ULT:
4276 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004277 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004278 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4279 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004280 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004281 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4282 break;
4283 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4284 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4285 return ReplaceInstUsesWith(I, LHS);
4286 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4287 break;
4288 }
4289 break;
4290 case ICmpInst::ICMP_SLT:
4291 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004292 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004293 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4294 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004295 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004296 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4297 break;
4298 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4299 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4300 return ReplaceInstUsesWith(I, LHS);
4301 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4302 break;
4303 }
4304 break;
4305 case ICmpInst::ICMP_UGT:
4306 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004307 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004308 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4309 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4310 return ReplaceInstUsesWith(I, RHS);
4311 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4312 break;
4313 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004314 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004315 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004316 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004317 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004318 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004319 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004320 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4321 break;
4322 }
4323 break;
4324 case ICmpInst::ICMP_SGT:
4325 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004326 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004327 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4328 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4329 return ReplaceInstUsesWith(I, RHS);
4330 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4331 break;
4332 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004333 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004334 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004335 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004336 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004337 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004338 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004339 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4340 break;
4341 }
4342 break;
4343 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004344
4345 return 0;
4346}
4347
Chris Lattner42d1be02009-07-23 05:14:02 +00004348Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4349 FCmpInst *RHS) {
4350
4351 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4352 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4353 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4354 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4355 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4356 // If either of the constants are nans, then the whole thing returns
4357 // false.
4358 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004359 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004360 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004361 LHS->getOperand(0), RHS->getOperand(0));
4362 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004363
4364 // Handle vector zeros. This occurs because the canonical form of
4365 // "fcmp ord x,x" is "fcmp ord x, 0".
4366 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4367 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004368 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004369 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004370 return 0;
4371 }
4372
4373 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4374 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4375 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4376
4377
4378 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4379 // Swap RHS operands to match LHS.
4380 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4381 std::swap(Op1LHS, Op1RHS);
4382 }
4383
4384 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4385 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4386 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004387 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004388
4389 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004390 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004391 if (Op0CC == FCmpInst::FCMP_TRUE)
4392 return ReplaceInstUsesWith(I, RHS);
4393 if (Op1CC == FCmpInst::FCMP_TRUE)
4394 return ReplaceInstUsesWith(I, LHS);
4395
4396 bool Op0Ordered;
4397 bool Op1Ordered;
4398 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4399 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4400 if (Op1Pred == 0) {
4401 std::swap(LHS, RHS);
4402 std::swap(Op0Pred, Op1Pred);
4403 std::swap(Op0Ordered, Op1Ordered);
4404 }
4405 if (Op0Pred == 0) {
4406 // uno && ueq -> uno && (uno || eq) -> ueq
4407 // ord && olt -> ord && (ord && lt) -> olt
4408 if (Op0Ordered == Op1Ordered)
4409 return ReplaceInstUsesWith(I, RHS);
4410
4411 // uno && oeq -> uno && (ord && eq) -> false
4412 // uno && ord -> false
4413 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004414 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004415 // ord && ueq -> ord && (uno || eq) -> oeq
4416 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4417 Op0LHS, Op0RHS, Context));
4418 }
4419 }
4420
4421 return 0;
4422}
4423
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004424
Chris Lattner7e708292002-06-25 16:13:24 +00004425Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004426 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004427 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004428
Chris Lattnerd06094f2009-11-10 00:55:12 +00004429 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4430 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004431
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004432 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004433 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004434 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00004435 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00004436
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004437 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004438 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004439 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004440
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004441 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004442 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004443 Value *Op0LHS = Op0I->getOperand(0);
4444 Value *Op0RHS = Op0I->getOperand(1);
4445 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004446 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004447 case Instruction::Xor:
4448 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004449 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004450 if (!Op0I->hasOneUse()) break;
4451
4452 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4453 // Not masking anything out for the LHS, move to RHS.
4454 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4455 Op0RHS->getName()+".masked");
4456 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4457 }
4458 if (!isa<Constant>(Op0RHS) &&
4459 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4460 // Not masking anything out for the RHS, move to LHS.
4461 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4462 Op0LHS->getName()+".masked");
4463 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004464 }
4465
Chris Lattner6e7ba452005-01-01 16:22:27 +00004466 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004467 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004468 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4469 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4470 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4471 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004472 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004473 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004474 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004475 break;
4476
4477 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004478 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4479 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4480 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4481 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004482 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004483
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004484 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4485 // has 1's for all bits that the subtraction with A might affect.
4486 if (Op0I->hasOneUse()) {
4487 uint32_t BitWidth = AndRHSMask.getBitWidth();
4488 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4489 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4490
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004491 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004492 if (!(A && A->isZero()) && // avoid infinite recursion.
4493 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004494 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004495 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4496 }
4497 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004498 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004499
4500 case Instruction::Shl:
4501 case Instruction::LShr:
4502 // (1 << x) & 1 --> zext(x == 0)
4503 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004504 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004505 Value *NewICmp =
4506 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004507 return new ZExtInst(NewICmp, I.getType());
4508 }
4509 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004510 }
4511
Chris Lattner58403262003-07-23 19:25:52 +00004512 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004513 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004514 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004515 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004516 // If this is an integer truncation or change from signed-to-unsigned, and
4517 // if the source is an and/or with immediate, transform it. This
4518 // frequently occurs for bitfield accesses.
4519 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004520 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004521 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004522 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004523 if (CastOp->getOpcode() == Instruction::And) {
4524 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004525 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4526 // This will fold the two constants together, which may allow
4527 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004528 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004529 CastOp->getOperand(0), I.getType(),
4530 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004531 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004532 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004533 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004534 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004535 } else if (CastOp->getOpcode() == Instruction::Or) {
4536 // Change: and (cast (or X, C1) to T), C2
4537 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004538 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004539 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004540 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004541 return ReplaceInstUsesWith(I, AndRHS);
4542 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004543 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004544 }
Chris Lattner06782f82003-07-23 19:36:21 +00004545 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004546
4547 // Try to fold constant and into select arguments.
4548 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004549 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004550 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004551 if (isa<PHINode>(Op0))
4552 if (Instruction *NV = FoldOpIntoPhi(I))
4553 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004554 }
4555
Chris Lattner5b62aa72004-06-18 06:07:51 +00004556
Misha Brukmancb6267b2004-07-30 12:50:08 +00004557 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004558 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4559 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4560 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4561 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4562 I.getName()+".demorgan");
4563 return BinaryOperator::CreateNot(Or);
4564 }
4565
Chris Lattner2082ad92006-02-13 23:07:23 +00004566 {
Chris Lattner003b6202007-06-15 05:58:24 +00004567 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004568 // (A|B) & ~(A&B) -> A^B
4569 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4570 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4571 ((A == C && B == D) || (A == D && B == C)))
4572 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004573
Chris Lattnerd06094f2009-11-10 00:55:12 +00004574 // ~(A&B) & (A|B) -> A^B
4575 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4576 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4577 ((A == C && B == D) || (A == D && B == C)))
4578 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004579
4580 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004581 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004582 if (A == Op1) { // (A^B)&A -> A&(A^B)
4583 I.swapOperands(); // Simplify below
4584 std::swap(Op0, Op1);
4585 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4586 cast<BinaryOperator>(Op0)->swapOperands();
4587 I.swapOperands(); // Simplify below
4588 std::swap(Op0, Op1);
4589 }
4590 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004591
Chris Lattner64daab52006-04-01 08:03:55 +00004592 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004593 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004594 if (B == Op0) { // B&(A^B) -> B&(B^A)
4595 cast<BinaryOperator>(Op1)->swapOperands();
4596 std::swap(A, B);
4597 }
Chris Lattner74381062009-08-30 07:44:24 +00004598 if (A == Op0) // A&(A^B) -> A & ~B
4599 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004600 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004601
4602 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004603 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4604 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004605 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004606 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4607 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004608 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004609 }
4610
Reid Spencere4d87aa2006-12-23 06:05:41 +00004611 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4612 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004613 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004614 return R;
4615
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004616 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4617 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4618 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004619 }
4620
Chris Lattner6fc205f2006-05-05 06:39:07 +00004621 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004622 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4623 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4624 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4625 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004626 if (SrcTy == Op1C->getOperand(0)->getType() &&
4627 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004628 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004629 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4630 I.getType(), TD) &&
4631 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4632 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004633 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4634 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004635 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004636 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004637 }
Chris Lattnere511b742006-11-14 07:46:50 +00004638
4639 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004640 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4641 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4642 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004643 SI0->getOperand(1) == SI1->getOperand(1) &&
4644 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004645 Value *NewOp =
4646 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4647 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004648 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004649 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004650 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004651 }
4652
Evan Cheng8db90722008-10-14 17:15:11 +00004653 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004654 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004655 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4656 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4657 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004658 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004659
Chris Lattner7e708292002-06-25 16:13:24 +00004660 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004661}
4662
Chris Lattner8c34cd22008-10-05 02:13:19 +00004663/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4664/// capable of providing pieces of a bswap. The subexpression provides pieces
4665/// of a bswap if it is proven that each of the non-zero bytes in the output of
4666/// the expression came from the corresponding "byte swapped" byte in some other
4667/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4668/// we know that the expression deposits the low byte of %X into the high byte
4669/// of the bswap result and that all other bytes are zero. This expression is
4670/// accepted, the high byte of ByteValues is set to X to indicate a correct
4671/// match.
4672///
4673/// This function returns true if the match was unsuccessful and false if so.
4674/// On entry to the function the "OverallLeftShift" is a signed integer value
4675/// indicating the number of bytes that the subexpression is later shifted. For
4676/// example, if the expression is later right shifted by 16 bits, the
4677/// OverallLeftShift value would be -2 on entry. This is used to specify which
4678/// byte of ByteValues is actually being set.
4679///
4680/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4681/// byte is masked to zero by a user. For example, in (X & 255), X will be
4682/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4683/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4684/// always in the local (OverallLeftShift) coordinate space.
4685///
4686static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4687 SmallVector<Value*, 8> &ByteValues) {
4688 if (Instruction *I = dyn_cast<Instruction>(V)) {
4689 // If this is an or instruction, it may be an inner node of the bswap.
4690 if (I->getOpcode() == Instruction::Or) {
4691 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4692 ByteValues) ||
4693 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4694 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004695 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004696
4697 // If this is a logical shift by a constant multiple of 8, recurse with
4698 // OverallLeftShift and ByteMask adjusted.
4699 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4700 unsigned ShAmt =
4701 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4702 // Ensure the shift amount is defined and of a byte value.
4703 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4704 return true;
4705
4706 unsigned ByteShift = ShAmt >> 3;
4707 if (I->getOpcode() == Instruction::Shl) {
4708 // X << 2 -> collect(X, +2)
4709 OverallLeftShift += ByteShift;
4710 ByteMask >>= ByteShift;
4711 } else {
4712 // X >>u 2 -> collect(X, -2)
4713 OverallLeftShift -= ByteShift;
4714 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004715 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004716 }
4717
4718 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4719 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4720
4721 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4722 ByteValues);
4723 }
4724
4725 // If this is a logical 'and' with a mask that clears bytes, clear the
4726 // corresponding bytes in ByteMask.
4727 if (I->getOpcode() == Instruction::And &&
4728 isa<ConstantInt>(I->getOperand(1))) {
4729 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4730 unsigned NumBytes = ByteValues.size();
4731 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4732 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4733
4734 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4735 // If this byte is masked out by a later operation, we don't care what
4736 // the and mask is.
4737 if ((ByteMask & (1 << i)) == 0)
4738 continue;
4739
4740 // If the AndMask is all zeros for this byte, clear the bit.
4741 APInt MaskB = AndMask & Byte;
4742 if (MaskB == 0) {
4743 ByteMask &= ~(1U << i);
4744 continue;
4745 }
4746
4747 // If the AndMask is not all ones for this byte, it's not a bytezap.
4748 if (MaskB != Byte)
4749 return true;
4750
4751 // Otherwise, this byte is kept.
4752 }
4753
4754 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4755 ByteValues);
4756 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004757 }
4758
Chris Lattner8c34cd22008-10-05 02:13:19 +00004759 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4760 // the input value to the bswap. Some observations: 1) if more than one byte
4761 // is demanded from this input, then it could not be successfully assembled
4762 // into a byteswap. At least one of the two bytes would not be aligned with
4763 // their ultimate destination.
4764 if (!isPowerOf2_32(ByteMask)) return true;
4765 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004766
Chris Lattner8c34cd22008-10-05 02:13:19 +00004767 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4768 // is demanded, it needs to go into byte 0 of the result. This means that the
4769 // byte needs to be shifted until it lands in the right byte bucket. The
4770 // shift amount depends on the position: if the byte is coming from the high
4771 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4772 // low part, it must be shifted left.
4773 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4774 if (InputByteNo < ByteValues.size()/2) {
4775 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4776 return true;
4777 } else {
4778 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4779 return true;
4780 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004781
4782 // If the destination byte value is already defined, the values are or'd
4783 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004784 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004785 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004786 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004787 return false;
4788}
4789
4790/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4791/// If so, insert the new bswap intrinsic and return it.
4792Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004793 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004794 if (!ITy || ITy->getBitWidth() % 16 ||
4795 // ByteMask only allows up to 32-byte values.
4796 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004797 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004798
4799 /// ByteValues - For each byte of the result, we keep track of which value
4800 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004801 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004802 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004803
4804 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004805 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4806 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004807 return 0;
4808
4809 // Check to see if all of the bytes come from the same value.
4810 Value *V = ByteValues[0];
4811 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4812
4813 // Check to make sure that all of the bytes come from the same value.
4814 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4815 if (ByteValues[i] != V)
4816 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004817 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004818 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004819 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004820 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004821}
4822
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004823/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4824/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4825/// we can simplify this expression to "cond ? C : D or B".
4826static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004827 Value *C, Value *D,
4828 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004829 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004830 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004831 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004832 return 0;
4833
Chris Lattnera6a474d2008-11-16 04:26:55 +00004834 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004835 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004836 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004837 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004838 return SelectInst::Create(Cond, C, B);
4839 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004840 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004841 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004842 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004843 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004844 return 0;
4845}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004846
Chris Lattner69d4ced2008-11-16 05:20:07 +00004847/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4848Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4849 ICmpInst *LHS, ICmpInst *RHS) {
4850 Value *Val, *Val2;
4851 ConstantInt *LHSCst, *RHSCst;
4852 ICmpInst::Predicate LHSCC, RHSCC;
4853
4854 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004855 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4856 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004857 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004858
4859
4860 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4861 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4862 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4863 Value *NewOr = Builder->CreateOr(Val, Val2);
4864 return new ICmpInst(LHSCC, NewOr, LHSCst);
4865 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004866
4867 // From here on, we only handle:
4868 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4869 if (Val != Val2) return 0;
4870
4871 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4872 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4873 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4874 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4875 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4876 return 0;
4877
4878 // We can't fold (ugt x, C) | (sgt x, C2).
4879 if (!PredicatesFoldable(LHSCC, RHSCC))
4880 return 0;
4881
4882 // Ensure that the larger constant is on the RHS.
4883 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004884 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004885 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004886 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004887 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4888 else
4889 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4890
4891 if (ShouldSwap) {
4892 std::swap(LHS, RHS);
4893 std::swap(LHSCst, RHSCst);
4894 std::swap(LHSCC, RHSCC);
4895 }
4896
4897 // At this point, we know we have have two icmp instructions
4898 // comparing a value against two constants and or'ing the result
4899 // together. Because of the above check, we know that we only have
4900 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4901 // FoldICmpLogical check above), that the two constants are not
4902 // equal.
4903 assert(LHSCst != RHSCst && "Compares not folded above?");
4904
4905 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004906 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004907 case ICmpInst::ICMP_EQ:
4908 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004909 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004910 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004911 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004912 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004913 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004914 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004915 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004916 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004917 }
4918 break; // (X == 13 | X == 15) -> no change
4919 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4920 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4921 break;
4922 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4923 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4924 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4925 return ReplaceInstUsesWith(I, RHS);
4926 }
4927 break;
4928 case ICmpInst::ICMP_NE:
4929 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004930 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004931 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4932 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4933 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4934 return ReplaceInstUsesWith(I, LHS);
4935 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4936 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4937 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004938 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004939 }
4940 break;
4941 case ICmpInst::ICMP_ULT:
4942 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004943 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004944 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4945 break;
4946 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4947 // If RHSCst is [us]MAXINT, it is always false. Not handling
4948 // this can cause overflow.
4949 if (RHSCst->isMaxValue(false))
4950 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004951 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004952 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004953 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4954 break;
4955 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4956 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4957 return ReplaceInstUsesWith(I, RHS);
4958 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4959 break;
4960 }
4961 break;
4962 case ICmpInst::ICMP_SLT:
4963 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004964 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004965 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4966 break;
4967 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4968 // If RHSCst is [us]MAXINT, it is always false. Not handling
4969 // this can cause overflow.
4970 if (RHSCst->isMaxValue(true))
4971 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004972 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004973 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004974 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4975 break;
4976 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4977 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4978 return ReplaceInstUsesWith(I, RHS);
4979 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4980 break;
4981 }
4982 break;
4983 case ICmpInst::ICMP_UGT:
4984 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004985 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004986 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4987 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4988 return ReplaceInstUsesWith(I, LHS);
4989 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4990 break;
4991 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4992 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004993 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004994 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4995 break;
4996 }
4997 break;
4998 case ICmpInst::ICMP_SGT:
4999 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005000 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00005001 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
5002 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5003 return ReplaceInstUsesWith(I, LHS);
5004 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5005 break;
5006 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5007 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005008 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00005009 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5010 break;
5011 }
5012 break;
5013 }
5014 return 0;
5015}
5016
Chris Lattner5414cc52009-07-23 05:46:22 +00005017Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5018 FCmpInst *RHS) {
5019 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5020 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5021 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5022 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5023 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5024 // If either of the constants are nans, then the whole thing returns
5025 // true.
5026 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00005027 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005028
5029 // Otherwise, no need to compare the two constants, compare the
5030 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005031 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005032 LHS->getOperand(0), RHS->getOperand(0));
5033 }
5034
5035 // Handle vector zeros. This occurs because the canonical form of
5036 // "fcmp uno x,x" is "fcmp uno x, 0".
5037 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5038 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005039 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005040 LHS->getOperand(0), RHS->getOperand(0));
5041
5042 return 0;
5043 }
5044
5045 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5046 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5047 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5048
5049 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5050 // Swap RHS operands to match LHS.
5051 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5052 std::swap(Op1LHS, Op1RHS);
5053 }
5054 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5055 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5056 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005057 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00005058 Op0LHS, Op0RHS);
5059 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005060 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005061 if (Op0CC == FCmpInst::FCMP_FALSE)
5062 return ReplaceInstUsesWith(I, RHS);
5063 if (Op1CC == FCmpInst::FCMP_FALSE)
5064 return ReplaceInstUsesWith(I, LHS);
5065 bool Op0Ordered;
5066 bool Op1Ordered;
5067 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5068 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5069 if (Op0Ordered == Op1Ordered) {
5070 // If both are ordered or unordered, return a new fcmp with
5071 // or'ed predicates.
5072 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5073 Op0LHS, Op0RHS, Context);
5074 if (Instruction *I = dyn_cast<Instruction>(RV))
5075 return I;
5076 // Otherwise, it's a constant boolean value...
5077 return ReplaceInstUsesWith(I, RV);
5078 }
5079 }
5080 return 0;
5081}
5082
Bill Wendlinga698a472008-12-01 08:23:25 +00005083/// FoldOrWithConstants - This helper function folds:
5084///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005085/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005086///
5087/// into:
5088///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005089/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005090///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005091/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005092Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005093 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005094 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5095 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005096
Bill Wendling286a0542008-12-02 06:24:20 +00005097 Value *V1 = 0;
5098 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005099 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005100
Bill Wendling29976b92008-12-02 06:18:11 +00005101 APInt Xor = CI1->getValue() ^ CI2->getValue();
5102 if (!Xor.isAllOnesValue()) return 0;
5103
Bill Wendling286a0542008-12-02 06:24:20 +00005104 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005105 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005106 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005107 }
5108
5109 return 0;
5110}
5111
Chris Lattner7e708292002-06-25 16:13:24 +00005112Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005113 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005114 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005115
Chris Lattnerd06094f2009-11-10 00:55:12 +00005116 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5117 return ReplaceInstUsesWith(I, V);
5118
5119
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005120 // See if we can simplify any instructions used by the instruction whose sole
5121 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005122 if (SimplifyDemandedInstructionBits(I))
5123 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005124
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005125 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005126 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005127 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005128 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005129 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005130 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005131 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005132 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005133 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005134 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005135
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005136 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005137 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005138 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005139 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005140 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005141 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005142 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005143 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005144
5145 // Try to fold constant and into select arguments.
5146 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005147 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005148 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005149 if (isa<PHINode>(Op0))
5150 if (Instruction *NV = FoldOpIntoPhi(I))
5151 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005152 }
5153
Chris Lattner4f637d42006-01-06 17:59:59 +00005154 Value *A = 0, *B = 0;
5155 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005156
Chris Lattner6423d4c2006-07-10 20:25:24 +00005157 // (A | B) | C and A | (B | C) -> bswap if possible.
5158 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005159 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5160 match(Op1, m_Or(m_Value(), m_Value())) ||
5161 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5162 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005163 if (Instruction *BSwap = MatchBSwap(I))
5164 return BSwap;
5165 }
5166
Chris Lattner6e4c6492005-05-09 04:58:36 +00005167 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005168 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005169 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005170 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005171 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005172 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005173 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005174 }
5175
5176 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005177 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005178 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005179 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005180 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005181 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005182 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005183 }
5184
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005185 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005186 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005187 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5188 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005189 Value *V1 = 0, *V2 = 0, *V3 = 0;
5190 C1 = dyn_cast<ConstantInt>(C);
5191 C2 = dyn_cast<ConstantInt>(D);
5192 if (C1 && C2) { // (A & C1)|(B & C2)
5193 // If we have: ((V + N) & C1) | (V & C2)
5194 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5195 // replace with V+N.
5196 if (C1->getValue() == ~C2->getValue()) {
5197 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005198 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005199 // Add commutes, try both ways.
5200 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5201 return ReplaceInstUsesWith(I, A);
5202 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5203 return ReplaceInstUsesWith(I, A);
5204 }
5205 // Or commutes, try both ways.
5206 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005207 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005208 // Add commutes, try both ways.
5209 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5210 return ReplaceInstUsesWith(I, B);
5211 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5212 return ReplaceInstUsesWith(I, B);
5213 }
5214 }
Chris Lattner044e5332007-04-08 08:01:49 +00005215 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005216 }
5217
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005218 // Check to see if we have any common things being and'ed. If so, find the
5219 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005220 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5221 if (A == B) // (A & C)|(A & D) == A & (C|D)
5222 V1 = A, V2 = C, V3 = D;
5223 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5224 V1 = A, V2 = B, V3 = C;
5225 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5226 V1 = C, V2 = A, V3 = D;
5227 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5228 V1 = C, V2 = A, V3 = B;
5229
5230 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005231 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005232 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005233 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005234 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005235
Dan Gohman1975d032008-10-30 20:40:10 +00005236 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005237 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005238 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005239 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005240 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005241 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005242 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005243 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005244 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005245
Bill Wendlingb01865c2008-11-30 13:52:49 +00005246 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005247 if ((match(C, m_Not(m_Specific(D))) &&
5248 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005249 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005250 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005251 if ((match(A, m_Not(m_Specific(D))) &&
5252 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005253 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005254 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005255 if ((match(C, m_Not(m_Specific(B))) &&
5256 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005257 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005258 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005259 if ((match(A, m_Not(m_Specific(B))) &&
5260 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005261 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005262 }
Chris Lattnere511b742006-11-14 07:46:50 +00005263
5264 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005265 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5266 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5267 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005268 SI0->getOperand(1) == SI1->getOperand(1) &&
5269 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005270 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5271 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005272 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005273 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005274 }
5275 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005276
Bill Wendlingb3833d12008-12-01 01:07:11 +00005277 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005278 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5279 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005280 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005281 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005282 }
5283 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005284 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5285 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005286 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005287 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005288 }
5289
Chris Lattnerd06094f2009-11-10 00:55:12 +00005290 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5291 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5292 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5293 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5294 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5295 I.getName()+".demorgan");
5296 return BinaryOperator::CreateNot(And);
5297 }
Chris Lattnera2881962003-02-18 19:28:33 +00005298
Reid Spencere4d87aa2006-12-23 06:05:41 +00005299 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5300 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005301 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005302 return R;
5303
Chris Lattner69d4ced2008-11-16 05:20:07 +00005304 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5305 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5306 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005307 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005308
5309 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005310 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005311 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005312 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005313 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5314 !isa<ICmpInst>(Op1C->getOperand(0))) {
5315 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005316 if (SrcTy == Op1C->getOperand(0)->getType() &&
5317 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005318 // Only do this if the casts both really cause code to be
5319 // generated.
5320 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5321 I.getType(), TD) &&
5322 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5323 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005324 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5325 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005326 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005327 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005328 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005329 }
Chris Lattner99c65742007-10-24 05:38:08 +00005330 }
5331
5332
5333 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5334 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005335 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5336 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5337 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005338 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005339
Chris Lattner7e708292002-06-25 16:13:24 +00005340 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005341}
5342
Dan Gohman844731a2008-05-13 00:00:25 +00005343namespace {
5344
Chris Lattnerc317d392004-02-16 01:20:27 +00005345// XorSelf - Implements: X ^ X --> 0
5346struct XorSelf {
5347 Value *RHS;
5348 XorSelf(Value *rhs) : RHS(rhs) {}
5349 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5350 Instruction *apply(BinaryOperator &Xor) const {
5351 return &Xor;
5352 }
5353};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005354
Dan Gohman844731a2008-05-13 00:00:25 +00005355}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005356
Chris Lattner7e708292002-06-25 16:13:24 +00005357Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005358 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005359 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005360
Evan Chengd34af782008-03-25 20:07:13 +00005361 if (isa<UndefValue>(Op1)) {
5362 if (isa<UndefValue>(Op0))
5363 // Handle undef ^ undef -> 0 special case. This is a common
5364 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005365 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005366 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005367 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005368
Chris Lattnerc317d392004-02-16 01:20:27 +00005369 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005370 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005371 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005372 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005373 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005374
5375 // See if we can simplify any instructions used by the instruction whose sole
5376 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005377 if (SimplifyDemandedInstructionBits(I))
5378 return &I;
5379 if (isa<VectorType>(I.getType()))
5380 if (isa<ConstantAggregateZero>(Op1))
5381 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005382
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005383 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005384 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005385 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5386 if (Op0I->getOpcode() == Instruction::And ||
5387 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005388 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5389 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5390 if (dyn_castNotVal(Op0I->getOperand(1)))
5391 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005392 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005393 Value *NotY =
5394 Builder->CreateNot(Op0I->getOperand(1),
5395 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005396 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005397 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005398 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005399 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005400
5401 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5402 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5403 if (isFreeToInvert(Op0I->getOperand(0)) &&
5404 isFreeToInvert(Op0I->getOperand(1))) {
5405 Value *NotX =
5406 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5407 Value *NotY =
5408 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5409 if (Op0I->getOpcode() == Instruction::And)
5410 return BinaryOperator::CreateOr(NotX, NotY);
5411 return BinaryOperator::CreateAnd(NotX, NotY);
5412 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005413 }
5414 }
5415 }
5416
5417
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005418 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005419 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005420 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005421 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005422 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005423 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005424
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005425 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005426 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005427 FCI->getOperand(0), FCI->getOperand(1));
5428 }
5429
Nick Lewycky517e1f52008-05-31 19:01:33 +00005430 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5431 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5432 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5433 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5434 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005435 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5436 (RHS == ConstantExpr::getCast(Opcode,
5437 ConstantInt::getTrue(*Context),
5438 Op0C->getDestTy()))) {
5439 CI->setPredicate(CI->getInversePredicate());
5440 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005441 }
5442 }
5443 }
5444 }
5445
Reid Spencere4d87aa2006-12-23 06:05:41 +00005446 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005447 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005448 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5449 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005450 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5451 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005452 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005453 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005454 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005455
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005456 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005457 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005458 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005459 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005460 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005461 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005462 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005463 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005464 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005465 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005466 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005467 Constant *C = ConstantInt::get(*Context,
5468 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005469 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005470
Chris Lattner7c4049c2004-01-12 19:35:11 +00005471 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005472 } else if (Op0I->getOpcode() == Instruction::Or) {
5473 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005474 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005475 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005476 // Anything in both C1 and C2 is known to be zero, remove it from
5477 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005478 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5479 NewRHS = ConstantExpr::getAnd(NewRHS,
5480 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005481 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005482 I.setOperand(0, Op0I->getOperand(0));
5483 I.setOperand(1, NewRHS);
5484 return &I;
5485 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005486 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005487 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005488 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005489
5490 // Try to fold constant and into select arguments.
5491 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005492 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005493 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005494 if (isa<PHINode>(Op0))
5495 if (Instruction *NV = FoldOpIntoPhi(I))
5496 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005497 }
5498
Dan Gohman186a6362009-08-12 16:04:34 +00005499 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005500 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005501 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005502
Dan Gohman186a6362009-08-12 16:04:34 +00005503 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005504 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005505 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005506
Chris Lattner318bf792007-03-18 22:51:34 +00005507
5508 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5509 if (Op1I) {
5510 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005511 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005512 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005513 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005514 I.swapOperands();
5515 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005516 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005517 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005518 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005519 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005520 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005521 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005522 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005523 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005524 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005525 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005526 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005527 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005528 std::swap(A, B);
5529 }
Chris Lattner318bf792007-03-18 22:51:34 +00005530 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005531 I.swapOperands(); // Simplified below.
5532 std::swap(Op0, Op1);
5533 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005534 }
Chris Lattner318bf792007-03-18 22:51:34 +00005535 }
5536
5537 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5538 if (Op0I) {
5539 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005540 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005541 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005542 if (A == Op1) // (B|A)^B == (A|B)^B
5543 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005544 if (B == Op1) // (A|B)^B == A & ~B
5545 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005546 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005547 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005548 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005549 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005550 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005551 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005552 if (A == Op1) // (A&B)^A -> (B&A)^A
5553 std::swap(A, B);
5554 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005555 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005556 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005557 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005558 }
Chris Lattner318bf792007-03-18 22:51:34 +00005559 }
5560
5561 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5562 if (Op0I && Op1I && Op0I->isShift() &&
5563 Op0I->getOpcode() == Op1I->getOpcode() &&
5564 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5565 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005566 Value *NewOp =
5567 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5568 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005569 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005570 Op1I->getOperand(1));
5571 }
5572
5573 if (Op0I && Op1I) {
5574 Value *A, *B, *C, *D;
5575 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005576 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5577 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005578 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005579 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005580 }
5581 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005582 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5583 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005584 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005585 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005586 }
5587
5588 // (A & B)^(C & D)
5589 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005590 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5591 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005592 // (X & Y)^(X & Y) -> (Y^Z) & X
5593 Value *X = 0, *Y = 0, *Z = 0;
5594 if (A == C)
5595 X = A, Y = B, Z = D;
5596 else if (A == D)
5597 X = A, Y = B, Z = C;
5598 else if (B == C)
5599 X = B, Y = A, Z = D;
5600 else if (B == D)
5601 X = B, Y = A, Z = C;
5602
5603 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005604 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005605 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005606 }
5607 }
5608 }
5609
Reid Spencere4d87aa2006-12-23 06:05:41 +00005610 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5611 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005612 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005613 return R;
5614
Chris Lattner6fc205f2006-05-05 06:39:07 +00005615 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005616 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005617 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005618 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5619 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005620 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005621 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005622 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5623 I.getType(), TD) &&
5624 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5625 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005626 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5627 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005628 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005629 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005630 }
Chris Lattner99c65742007-10-24 05:38:08 +00005631 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005632
Chris Lattner7e708292002-06-25 16:13:24 +00005633 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005634}
5635
Owen Andersond672ecb2009-07-03 00:17:18 +00005636static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005637 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005638 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005639}
Chris Lattnera96879a2004-09-29 17:40:11 +00005640
Dan Gohman6de29f82009-06-15 22:12:54 +00005641static bool HasAddOverflow(ConstantInt *Result,
5642 ConstantInt *In1, ConstantInt *In2,
5643 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005644 if (IsSigned)
5645 if (In2->getValue().isNegative())
5646 return Result->getValue().sgt(In1->getValue());
5647 else
5648 return Result->getValue().slt(In1->getValue());
5649 else
5650 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005651}
5652
Dan Gohman6de29f82009-06-15 22:12:54 +00005653/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005654/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005655static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005656 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005657 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005658 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005659
Dan Gohman6de29f82009-06-15 22:12:54 +00005660 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5661 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005662 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005663 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5664 ExtractElement(In1, Idx, Context),
5665 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005666 IsSigned))
5667 return true;
5668 }
5669 return false;
5670 }
5671
5672 return HasAddOverflow(cast<ConstantInt>(Result),
5673 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5674 IsSigned);
5675}
5676
5677static bool HasSubOverflow(ConstantInt *Result,
5678 ConstantInt *In1, ConstantInt *In2,
5679 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005680 if (IsSigned)
5681 if (In2->getValue().isNegative())
5682 return Result->getValue().slt(In1->getValue());
5683 else
5684 return Result->getValue().sgt(In1->getValue());
5685 else
5686 return Result->getValue().ugt(In1->getValue());
5687}
5688
Dan Gohman6de29f82009-06-15 22:12:54 +00005689/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5690/// overflowed for this type.
5691static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005692 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005693 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005694 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005695
5696 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5697 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005698 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005699 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5700 ExtractElement(In1, Idx, Context),
5701 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005702 IsSigned))
5703 return true;
5704 }
5705 return false;
5706 }
5707
5708 return HasSubOverflow(cast<ConstantInt>(Result),
5709 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5710 IsSigned);
5711}
5712
Chris Lattner10c0d912008-04-22 02:53:33 +00005713
Reid Spencere4d87aa2006-12-23 06:05:41 +00005714/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005715/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005716Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005717 ICmpInst::Predicate Cond,
5718 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005719 // Look through bitcasts.
5720 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5721 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005722
Chris Lattner574da9b2005-01-13 20:14:25 +00005723 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005724 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005725 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005726 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005727 // know pointers can't overflow since the gep is inbounds. See if we can
5728 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005729 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5730
5731 // If not, synthesize the offset the hard way.
5732 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005733 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005734 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005735 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005736 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005737 // If the base pointers are different, but the indices are the same, just
5738 // compare the base pointer.
5739 if (PtrBase != GEPRHS->getOperand(0)) {
5740 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005741 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005742 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005743 if (IndicesTheSame)
5744 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5745 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5746 IndicesTheSame = false;
5747 break;
5748 }
5749
5750 // If all indices are the same, just compare the base pointers.
5751 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005752 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005753 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005754
5755 // Otherwise, the base pointers are different and the indices are
5756 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005757 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005758 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005759
Chris Lattnere9d782b2005-01-13 22:25:21 +00005760 // If one of the GEPs has all zero indices, recurse.
5761 bool AllZeros = true;
5762 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5763 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5764 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5765 AllZeros = false;
5766 break;
5767 }
5768 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005769 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5770 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005771
5772 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005773 AllZeros = true;
5774 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5775 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5776 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5777 AllZeros = false;
5778 break;
5779 }
5780 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005781 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005782
Chris Lattner4401c9c2005-01-14 00:20:05 +00005783 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5784 // If the GEPs only differ by one index, compare it.
5785 unsigned NumDifferences = 0; // Keep track of # differences.
5786 unsigned DiffOperand = 0; // The operand that differs.
5787 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5788 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005789 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5790 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005791 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005792 NumDifferences = 2;
5793 break;
5794 } else {
5795 if (NumDifferences++) break;
5796 DiffOperand = i;
5797 }
5798 }
5799
5800 if (NumDifferences == 0) // SAME GEP?
5801 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005802 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005803 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005804
Chris Lattner4401c9c2005-01-14 00:20:05 +00005805 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005806 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5807 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005808 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005809 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005810 }
5811 }
5812
Reid Spencere4d87aa2006-12-23 06:05:41 +00005813 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005814 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005815 if (TD &&
5816 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005817 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5818 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005819 Value *L = EmitGEPOffset(GEPLHS, *this);
5820 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005821 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005822 }
5823 }
5824 return 0;
5825}
5826
Chris Lattnera5406232008-05-19 20:18:56 +00005827/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5828///
5829Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5830 Instruction *LHSI,
5831 Constant *RHSC) {
5832 if (!isa<ConstantFP>(RHSC)) return 0;
5833 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5834
5835 // Get the width of the mantissa. We don't want to hack on conversions that
5836 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005837 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005838 if (MantissaWidth == -1) return 0; // Unknown.
5839
5840 // Check to see that the input is converted from an integer type that is small
5841 // enough that preserves all bits. TODO: check here for "known" sign bits.
5842 // 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 +00005843 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005844
5845 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005846 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5847 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005848 ++InputSize;
5849
5850 // If the conversion would lose info, don't hack on this.
5851 if ((int)InputSize > MantissaWidth)
5852 return 0;
5853
5854 // Otherwise, we can potentially simplify the comparison. We know that it
5855 // will always come through as an integer value and we know the constant is
5856 // not a NAN (it would have been previously simplified).
5857 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5858
5859 ICmpInst::Predicate Pred;
5860 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005861 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005862 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005863 case FCmpInst::FCMP_OEQ:
5864 Pred = ICmpInst::ICMP_EQ;
5865 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005866 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005867 case FCmpInst::FCMP_OGT:
5868 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5869 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005870 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005871 case FCmpInst::FCMP_OGE:
5872 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5873 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005874 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005875 case FCmpInst::FCMP_OLT:
5876 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5877 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005878 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005879 case FCmpInst::FCMP_OLE:
5880 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5881 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005882 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005883 case FCmpInst::FCMP_ONE:
5884 Pred = ICmpInst::ICMP_NE;
5885 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005886 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005887 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005888 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005889 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005890 }
5891
5892 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5893
5894 // Now we know that the APFloat is a normal number, zero or inf.
5895
Chris Lattner85162782008-05-20 03:50:52 +00005896 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005897 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005898 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005899
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005900 if (!LHSUnsigned) {
5901 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5902 // and large values.
5903 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5904 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5905 APFloat::rmNearestTiesToEven);
5906 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5907 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5908 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005909 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5910 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005911 }
5912 } else {
5913 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5914 // +INF and large values.
5915 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5916 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5917 APFloat::rmNearestTiesToEven);
5918 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5919 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5920 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005921 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5922 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005923 }
Chris Lattnera5406232008-05-19 20:18:56 +00005924 }
5925
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005926 if (!LHSUnsigned) {
5927 // See if the RHS value is < SignedMin.
5928 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5929 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5930 APFloat::rmNearestTiesToEven);
5931 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5932 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5933 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005934 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5935 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005936 }
Chris Lattnera5406232008-05-19 20:18:56 +00005937 }
5938
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005939 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5940 // [0, UMAX], but it may still be fractional. See if it is fractional by
5941 // casting the FP value to the integer value and back, checking for equality.
5942 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005943 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005944 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5945 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005946 if (!RHS.isZero()) {
5947 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005948 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5949 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005950 if (!Equal) {
5951 // If we had a comparison against a fractional value, we have to adjust
5952 // the compare predicate and sometimes the value. RHSC is rounded towards
5953 // zero at this point.
5954 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005955 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005956 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005957 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005958 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005959 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005960 case ICmpInst::ICMP_ULE:
5961 // (float)int <= 4.4 --> int <= 4
5962 // (float)int <= -4.4 --> false
5963 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005964 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005965 break;
5966 case ICmpInst::ICMP_SLE:
5967 // (float)int <= 4.4 --> int <= 4
5968 // (float)int <= -4.4 --> int < -4
5969 if (RHS.isNegative())
5970 Pred = ICmpInst::ICMP_SLT;
5971 break;
5972 case ICmpInst::ICMP_ULT:
5973 // (float)int < -4.4 --> false
5974 // (float)int < 4.4 --> int <= 4
5975 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005976 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005977 Pred = ICmpInst::ICMP_ULE;
5978 break;
5979 case ICmpInst::ICMP_SLT:
5980 // (float)int < -4.4 --> int < -4
5981 // (float)int < 4.4 --> int <= 4
5982 if (!RHS.isNegative())
5983 Pred = ICmpInst::ICMP_SLE;
5984 break;
5985 case ICmpInst::ICMP_UGT:
5986 // (float)int > 4.4 --> int > 4
5987 // (float)int > -4.4 --> true
5988 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005989 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005990 break;
5991 case ICmpInst::ICMP_SGT:
5992 // (float)int > 4.4 --> int > 4
5993 // (float)int > -4.4 --> int >= -4
5994 if (RHS.isNegative())
5995 Pred = ICmpInst::ICMP_SGE;
5996 break;
5997 case ICmpInst::ICMP_UGE:
5998 // (float)int >= -4.4 --> true
5999 // (float)int >= 4.4 --> int > 4
6000 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00006001 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00006002 Pred = ICmpInst::ICMP_UGT;
6003 break;
6004 case ICmpInst::ICMP_SGE:
6005 // (float)int >= -4.4 --> int >= -4
6006 // (float)int >= 4.4 --> int > 4
6007 if (!RHS.isNegative())
6008 Pred = ICmpInst::ICMP_SGT;
6009 break;
6010 }
Chris Lattnera5406232008-05-19 20:18:56 +00006011 }
6012 }
6013
6014 // Lower this FP comparison into an appropriate integer version of the
6015 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006016 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00006017}
6018
Chris Lattner1f12e442010-01-02 08:12:04 +00006019
6020/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
6021/// cmp pred (load (gep GV, ...)), cmpcst
6022/// where GV is a global variable with a constant initializer. Try to simplify
6023/// this into one or two simpler comparisons that do not need the load. For
6024/// example, we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into
6025/// "icmp eq i, 3". We assume that eliminating a load is always goodness.
6026Instruction *InstCombiner::
6027FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
6028 CmpInst &ICI) {
6029
6030 // There are many forms of this optimization we can handle, for now, just do
6031 // the simple index into a single-dimensional array.
6032 //
6033 // Require: GEP GV, 0, i
6034 if (GEP->getNumOperands() != 3 ||
6035 !isa<ConstantInt>(GEP->getOperand(1)) ||
6036 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
6037 return 0;
6038
6039 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
6040 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
6041
6042
6043 // Variables for our state machines.
6044
Chris Lattnerbef37372010-01-02 09:35:17 +00006045 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6046 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
6047 // and 87 is the second (and last) index. FirstTrueElement is -1 when
6048 // undefined, otherwise set to the first true element. SecondTrueElement is
6049 // -1 when undefined, -2 when overdefined and >= 0 when that index is true.
6050 int FirstTrueElement = -1, SecondTrueElement = -1;
Chris Lattner1f12e442010-01-02 08:12:04 +00006051
Chris Lattnerbef37372010-01-02 09:35:17 +00006052 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6053 // form "i != 47 & i != 87". Same state transitions as for true elements.
6054 int FirstFalseElement = -1, SecondFalseElement = -1;
Chris Lattner1f12e442010-01-02 08:12:04 +00006055
Chris Lattner10d514e2010-01-02 08:56:52 +00006056 // MagicBitvector - This is a magic bitvector where we set a bit if the
6057 // comparison is true for element 'i'. If there are 64 elements or less in
6058 // the array, this will fully represent all the comparison results.
6059 uint64_t MagicBitvector = 0;
6060
6061
Chris Lattner1f12e442010-01-02 08:12:04 +00006062 // Scan the array and see if one of our patterns matches.
6063 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6064 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
6065 // Find out if the comparison would be true or false for the i'th element.
6066 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(),
6067 Init->getOperand(i),
6068 CompareRHS, TD);
6069 // If the result is undef for this element, ignore it.
6070 if (isa<UndefValue>(C)) continue;
6071
6072 // If we can't compute the result for any of the elements, we have to give
6073 // up evaluating the entire conditional.
6074 if (!isa<ConstantInt>(C)) return 0;
6075
6076 // Otherwise, we know if the comparison is true or false for this element,
6077 // update our state machines.
6078 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6079
6080 // State machine for single index comparison.
6081 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00006082 // Update the TrueElement state machine.
6083 if (FirstTrueElement == -1)
6084 FirstTrueElement = i;
6085 else if (SecondTrueElement == -1)
6086 SecondTrueElement = i;
6087 else
6088 SecondTrueElement = -2;
Chris Lattner1f12e442010-01-02 08:12:04 +00006089 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00006090 // Update the FalseElement state machine.
6091 if (FirstFalseElement == -1)
6092 FirstFalseElement = i;
6093 else if (SecondFalseElement == -1)
6094 SecondFalseElement = i;
6095 else
6096 SecondFalseElement = -2;
Chris Lattner1f12e442010-01-02 08:12:04 +00006097 }
6098
Chris Lattner10d514e2010-01-02 08:56:52 +00006099 // If this element is in range, update our magic bitvector.
6100 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00006101 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00006102
Chris Lattner1f12e442010-01-02 08:12:04 +00006103 // If all of our states become overdefined, bail out early.
Chris Lattnerbef37372010-01-02 09:35:17 +00006104 if (i >= 64 && SecondTrueElement == -2 && SecondFalseElement == -2)
Chris Lattner1f12e442010-01-02 08:12:04 +00006105 return 0;
6106 }
6107
6108 // Now that we've scanned the entire array, emit our new comparison(s). We
6109 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00006110 Value *Idx = GEP->getOperand(2);
6111
6112 // If the comparison is only true for one or two elements, emit direct
6113 // comparisons.
6114 if (SecondTrueElement != -2) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006115 // None true -> false.
Chris Lattnerbef37372010-01-02 09:35:17 +00006116 if (FirstTrueElement == -1)
Chris Lattner1f12e442010-01-02 08:12:04 +00006117 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6118
Chris Lattnerbef37372010-01-02 09:35:17 +00006119 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6120
Chris Lattner1f12e442010-01-02 08:12:04 +00006121 // True for one element -> 'i == 47'.
Chris Lattnerbef37372010-01-02 09:35:17 +00006122 if (SecondTrueElement == -1)
6123 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6124
6125 // True for two elements -> 'i == 47 | i == 72'.
6126 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6127 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6128 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6129 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006130 }
6131
Chris Lattnerbef37372010-01-02 09:35:17 +00006132 // If the comparison is only false for one or two elements, emit direct
6133 // comparisons.
6134 if (SecondFalseElement != -2) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006135 // None false -> true.
Chris Lattnerbef37372010-01-02 09:35:17 +00006136 if (FirstFalseElement == -1)
Chris Lattner1f12e442010-01-02 08:12:04 +00006137 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6138
Chris Lattnerbef37372010-01-02 09:35:17 +00006139 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6140
6141 // False for one element -> 'i != 47'.
6142 if (SecondFalseElement == -1)
6143 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6144
6145 // False for two elements -> 'i != 47 & i != 72'.
6146 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6147 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6148 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6149 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006150 }
6151
Chris Lattner10d514e2010-01-02 08:56:52 +00006152 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6153 // of this load, replace it with computation that does:
6154 // ((magic_cst >> i) & 1) != 0
6155 if (Init->getNumOperands() <= 32 ||
6156 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6157 const Type *Ty;
6158 if (Init->getNumOperands() <= 32)
6159 Ty = Type::getInt32Ty(Init->getContext());
6160 else
6161 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00006162 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00006163 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6164 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6165 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6166 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006167
Chris Lattnerbef37372010-01-02 09:35:17 +00006168 // TODO: Range check
6169 // TODO: GEP 0, i, 4
Chris Lattner1f12e442010-01-02 08:12:04 +00006170 return 0;
6171}
6172
6173
Reid Spencere4d87aa2006-12-23 06:05:41 +00006174Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006175 bool Changed = false;
6176
6177 /// Orders the operands of the compare so that they are listed from most
6178 /// complex to least complex. This puts constants before unary operators,
6179 /// before binary operators.
6180 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6181 I.swapOperands();
6182 Changed = true;
6183 }
6184
Chris Lattner8b170942002-08-09 23:47:40 +00006185 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006186
Chris Lattner210c5d42009-11-09 23:55:12 +00006187 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6188 return ReplaceInstUsesWith(I, V);
6189
Chris Lattner58e97462007-01-14 19:42:17 +00006190 // Simplify 'fcmp pred X, X'
6191 if (Op0 == Op1) {
6192 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006193 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006194 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6195 case FCmpInst::FCMP_ULT: // True if unordered or less than
6196 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6197 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6198 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6199 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006200 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006201 return &I;
6202
6203 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6204 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6205 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6206 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6207 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6208 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006209 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006210 return &I;
6211 }
6212 }
6213
Reid Spencere4d87aa2006-12-23 06:05:41 +00006214 // Handle fcmp with constant RHS
6215 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6216 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6217 switch (LHSI->getOpcode()) {
6218 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006219 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6220 // block. If in the same block, we're encouraging jump threading. If
6221 // not, we are just pessimizing the code by making an i1 phi.
6222 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006223 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006224 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006225 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006226 case Instruction::SIToFP:
6227 case Instruction::UIToFP:
6228 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6229 return NV;
6230 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00006231 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006232 // If either operand of the select is a constant, we can fold the
6233 // comparison into the select arms, which will cause one to be
6234 // constant folded and the select turned into a bitwise or.
6235 Value *Op1 = 0, *Op2 = 0;
6236 if (LHSI->hasOneUse()) {
6237 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6238 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006239 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006240 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006241 Op2 = Builder->CreateFCmp(I.getPredicate(),
6242 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006243 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6244 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006245 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006246 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006247 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6248 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006249 }
6250 }
6251
6252 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006253 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006254 break;
6255 }
Chris Lattner34e0c762010-01-02 08:20:51 +00006256 case Instruction::Load:
6257 if (GetElementPtrInst *GEP =
6258 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6259 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6260 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6261 !cast<LoadInst>(LHSI)->isVolatile())
6262 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6263 return Res;
6264 //errs() << "NOT HANDLED: " << *GV << "\n";
6265 //errs() << "\t" << *GEP << "\n";
6266 //errs() << "\t " << I << "\n\n\n";
6267 }
6268 break;
6269 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006270 }
6271
6272 return Changed ? &I : 0;
6273}
6274
6275Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006276 bool Changed = false;
6277
6278 /// Orders the operands of the compare so that they are listed from most
6279 /// complex to least complex. This puts constants before unary operators,
6280 /// before binary operators.
6281 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6282 I.swapOperands();
6283 Changed = true;
6284 }
6285
Reid Spencere4d87aa2006-12-23 06:05:41 +00006286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006287
Chris Lattner210c5d42009-11-09 23:55:12 +00006288 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6289 return ReplaceInstUsesWith(I, V);
6290
6291 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006292
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006294 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006295 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006296 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006297 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006298 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006299 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006300 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006301 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006302 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006303
Reid Spencere4d87aa2006-12-23 06:05:41 +00006304 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006305 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006306 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006307 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006308 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006309 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006310 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006311 case ICmpInst::ICMP_SGT:
6312 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006313 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006314 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006315 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006316 return BinaryOperator::CreateAnd(Not, Op0);
6317 }
6318 case ICmpInst::ICMP_UGE:
6319 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6320 // FALL THROUGH
6321 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006322 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006323 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006324 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006325 case ICmpInst::ICMP_SGE:
6326 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6327 // FALL THROUGH
6328 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006329 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006330 return BinaryOperator::CreateOr(Not, Op0);
6331 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006332 }
Chris Lattner8b170942002-08-09 23:47:40 +00006333 }
6334
Dan Gohman1c8491e2009-04-25 17:12:48 +00006335 unsigned BitWidth = 0;
6336 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006337 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6338 else if (Ty->isIntOrIntVector())
6339 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006340
6341 bool isSignBit = false;
6342
Dan Gohman81b28ce2008-09-16 18:46:06 +00006343 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006344 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006345 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006346
Chris Lattnerb6566012008-01-05 01:18:20 +00006347 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00006348 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006349 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006350 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006351 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006352 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006353
Dan Gohman81b28ce2008-09-16 18:46:06 +00006354 // If we have an icmp le or icmp ge instruction, turn it into the
6355 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006356 // them being folded in the code below. The SimplifyICmpInst code has
6357 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006358 switch (I.getPredicate()) {
6359 default: break;
6360 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006361 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006362 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006363 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006364 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006365 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006366 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006367 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006368 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006369 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006370 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006371 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006372 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006373 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006374 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006375 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006376 }
6377
Chris Lattner183661e2008-07-11 05:40:05 +00006378 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006379 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006380 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006381 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6382 }
6383
6384 // See if we can fold the comparison based on range information we can get
6385 // by checking whether bits are known to be zero or one in the input.
6386 if (BitWidth != 0) {
6387 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6388 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6389
6390 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006391 isSignBit ? APInt::getSignBit(BitWidth)
6392 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006393 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006394 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006395 if (SimplifyDemandedBits(I.getOperandUse(1),
6396 APInt::getAllOnesValue(BitWidth),
6397 Op1KnownZero, Op1KnownOne, 0))
6398 return &I;
6399
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006400 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006401 // in. Compute the Min, Max and RHS values based on the known bits. For the
6402 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006403 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6404 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006405 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006406 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6407 Op0Min, Op0Max);
6408 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6409 Op1Min, Op1Max);
6410 } else {
6411 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6412 Op0Min, Op0Max);
6413 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6414 Op1Min, Op1Max);
6415 }
6416
Chris Lattner183661e2008-07-11 05:40:05 +00006417 // If Min and Max are known to be the same, then SimplifyDemandedBits
6418 // figured out that the LHS is a constant. Just constant fold this now so
6419 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006420 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006421 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006422 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006423 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006424 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006425 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006426
Chris Lattner183661e2008-07-11 05:40:05 +00006427 // Based on the range information we know about the LHS, see if we can
6428 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006429 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006430 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006431 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006432 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006433 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006434 break;
6435 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006436 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006437 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006438 break;
6439 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006440 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006441 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006442 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006443 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006444 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006445 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006446 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6447 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006448 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006449 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006450
6451 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6452 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006454 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006455 }
Chris Lattner84dff672008-07-11 05:08:55 +00006456 break;
6457 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006458 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006459 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006460 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006461 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006462
6463 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006464 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006465 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6466 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006467 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006468 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006469
6470 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6471 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006472 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006473 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006474 }
Chris Lattner84dff672008-07-11 05:08:55 +00006475 break;
6476 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006477 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006478 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006479 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006480 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006481 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006482 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006483 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6484 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006485 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006486 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006487 }
Chris Lattner84dff672008-07-11 05:08:55 +00006488 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006489 case ICmpInst::ICMP_SGT:
6490 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006491 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006492 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006493 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006494
6495 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006496 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006497 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6498 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006499 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006500 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006501 }
6502 break;
6503 case ICmpInst::ICMP_SGE:
6504 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6505 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006506 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006507 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006508 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006509 break;
6510 case ICmpInst::ICMP_SLE:
6511 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6512 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006513 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006514 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006515 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006516 break;
6517 case ICmpInst::ICMP_UGE:
6518 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6519 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006520 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006521 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006522 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006523 break;
6524 case ICmpInst::ICMP_ULE:
6525 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6526 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006527 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006528 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006529 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006530 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006531 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006532
6533 // Turn a signed comparison into an unsigned one if both operands
6534 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006535 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006536 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6537 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006538 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006539 }
6540
6541 // Test if the ICmpInst instruction is used exclusively by a select as
6542 // part of a minimum or maximum operation. If so, refrain from doing
6543 // any other folding. This helps out other analyses which understand
6544 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6545 // and CodeGen. And in this case, at least one of the comparison
6546 // operands has at least one user besides the compare (the select),
6547 // which would often largely negate the benefit of folding anyway.
6548 if (I.hasOneUse())
6549 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6550 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6551 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6552 return 0;
6553
6554 // See if we are doing a comparison between a constant and an instruction that
6555 // can be folded into the comparison.
6556 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006557 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006558 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006559 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006560 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006561 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6562 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006563 }
6564
Chris Lattner01deb9d2007-04-03 17:43:25 +00006565 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006566 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6567 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6568 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006569 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00006570 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00006571 if (RHSC->isNullValue() &&
6572 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6573 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6574 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006575 break;
Chris Lattner6970b662005-04-23 15:31:55 +00006576 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006577 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006578 // block. If in the same block, we're encouraging jump threading. If
6579 // not, we are just pessimizing the code by making an i1 phi.
6580 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006581 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006582 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006583 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006584 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006585 // If either operand of the select is a constant, we can fold the
6586 // comparison into the select arms, which will cause one to be
6587 // constant folded and the select turned into a bitwise or.
6588 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006589 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6590 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6591 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6592 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6593
6594 // We only want to perform this transformation if it will not lead to
6595 // additional code. This is true if either both sides of the select
6596 // fold to a constant (in which case the icmp is replaced with a select
6597 // which will usually simplify) or this is the only user of the
6598 // select (in which case we are trading a select+icmp for a simpler
6599 // select+icmp).
6600 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6601 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006602 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6603 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006604 if (!Op2)
6605 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6606 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006607 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006608 }
Chris Lattner6970b662005-04-23 15:31:55 +00006609 break;
6610 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006611 case Instruction::Call:
6612 // If we have (malloc != null), and if the malloc has a single use, we
6613 // can assume it is successful and remove the malloc.
6614 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6615 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006616 // Need to explicitly erase malloc call here, instead of adding it to
6617 // Worklist, because it won't get DCE'd from the Worklist since
6618 // isInstructionTriviallyDead() returns false for function calls.
6619 // It is OK to replace LHSI/MallocCall with Undef because the
6620 // instruction that uses it will be erased via Worklist.
6621 if (extractMallocCall(LHSI)) {
6622 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6623 EraseInstFromFunction(*LHSI);
6624 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006625 ConstantInt::get(Type::getInt1Ty(*Context),
6626 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006627 }
6628 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6629 if (MallocCall->hasOneUse()) {
6630 MallocCall->replaceAllUsesWith(
6631 UndefValue::get(MallocCall->getType()));
6632 EraseInstFromFunction(*MallocCall);
6633 Worklist.Add(LHSI); // The malloc's bitcast use.
6634 return ReplaceInstUsesWith(I,
6635 ConstantInt::get(Type::getInt1Ty(*Context),
6636 !I.isTrueWhenEqual()));
6637 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006638 }
6639 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00006640 case Instruction::IntToPtr:
6641 // icmp pred inttoptr(X), null -> icmp pred X, 0
6642 if (RHSC->isNullValue() && TD &&
6643 TD->getIntPtrType(RHSC->getContext()) ==
6644 LHSI->getOperand(0)->getType())
6645 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6646 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6647 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00006648
6649 case Instruction::Load:
6650 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00006651 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006652 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6653 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattner34e0c762010-01-02 08:20:51 +00006654 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00006655 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6656 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006657 //errs() << "NOT HANDLED: " << *GV << "\n";
6658 //errs() << "\t" << *GEP << "\n";
6659 //errs() << "\t " << I << "\n\n\n";
6660 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006661 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006662 }
Chris Lattner6970b662005-04-23 15:31:55 +00006663 }
6664
Reid Spencere4d87aa2006-12-23 06:05:41 +00006665 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006666 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006667 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006668 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006669 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006670 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6671 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006672 return NI;
6673
Reid Spencere4d87aa2006-12-23 06:05:41 +00006674 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006675 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6676 // now.
6677 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6678 if (isa<PointerType>(Op0->getType()) &&
6679 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006680 // We keep moving the cast from the left operand over to the right
6681 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006682 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006683
Chris Lattner57d86372007-01-06 01:45:59 +00006684 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6685 // so eliminate it as well.
6686 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6687 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006688
Chris Lattnerde90b762003-11-03 04:25:02 +00006689 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006690 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006691 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006692 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006693 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006694 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006695 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006696 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006697 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006698 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006699 }
Chris Lattner57d86372007-01-06 01:45:59 +00006700 }
6701
6702 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006703 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006704 // This comes up when you have code like
6705 // int X = A < B;
6706 // if (X) ...
6707 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006708 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006709 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006710 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006711 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006712 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006713
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006714 // See if it's the same type of instruction on the left and right.
6715 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6716 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006717 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006718 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006719 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006720 default: break;
6721 case Instruction::Add:
6722 case Instruction::Sub:
6723 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006724 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006725 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006726 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006727 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6728 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6729 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006730 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006731 ? I.getUnsignedPredicate()
6732 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006733 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006734 Op1I->getOperand(0));
6735 }
6736
6737 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006738 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006739 ? I.getUnsignedPredicate()
6740 : I.getSignedPredicate();
6741 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006742 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006743 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006744 }
6745 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006746 break;
6747 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006748 if (!I.isEquality())
6749 break;
6750
Nick Lewycky5d52c452008-08-21 05:56:10 +00006751 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6752 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6753 // Mask = -1 >> count-trailing-zeros(Cst).
6754 if (!CI->isZero() && !CI->isOne()) {
6755 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006756 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006757 APInt::getLowBitsSet(AP.getBitWidth(),
6758 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006759 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006760 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6761 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006762 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006763 }
6764 }
6765 break;
6766 }
6767 }
6768 }
6769 }
6770
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006771 // ~x < ~y --> y < x
6772 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006773 if (match(Op0, m_Not(m_Value(A))) &&
6774 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006775 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006776 }
6777
Chris Lattner65b72ba2006-09-18 04:22:48 +00006778 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006779 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006780
6781 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006782 if (match(Op0, m_Neg(m_Value(A))) &&
6783 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006784 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006785
Dan Gohman4ae51262009-08-12 16:23:25 +00006786 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006787 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6788 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006789 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006790 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006791 }
6792
Dan Gohman4ae51262009-08-12 16:23:25 +00006793 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006794 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006795 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006796 if (match(B, m_ConstantInt(C1)) &&
6797 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006798 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006799 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006800 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6801 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006802 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006803
6804 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006805 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6806 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6807 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6808 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006809 }
6810 }
6811
Dan Gohman4ae51262009-08-12 16:23:25 +00006812 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006813 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006814 // A == (A^B) -> B == 0
6815 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006816 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006817 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006818 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006819
6820 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006821 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006822 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006823 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006824
6825 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006826 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006827 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006828 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006829
Chris Lattner9c2328e2006-11-14 06:06:06 +00006830 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6831 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006832 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6833 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006834 Value *X = 0, *Y = 0, *Z = 0;
6835
6836 if (A == C) {
6837 X = B; Y = D; Z = A;
6838 } else if (A == D) {
6839 X = B; Y = C; Z = A;
6840 } else if (B == C) {
6841 X = A; Y = D; Z = B;
6842 } else if (B == D) {
6843 X = A; Y = C; Z = B;
6844 }
6845
6846 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006847 Op1 = Builder->CreateXor(X, Y, "tmp");
6848 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006849 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006850 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006851 return &I;
6852 }
6853 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006854 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006855
6856 {
6857 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006858 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006859 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006860 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6861
Chris Lattner2799baf2009-12-21 03:19:28 +00006862 // icmp X, X+Cst
6863 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006864 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006865 }
Chris Lattner7e708292002-06-25 16:13:24 +00006866 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006867}
6868
Chris Lattner2799baf2009-12-21 03:19:28 +00006869/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6870Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6871 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006872 ICmpInst::Predicate Pred,
6873 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006874 // If we have X+0, exit early (simplifying logic below) and let it get folded
6875 // elsewhere. icmp X+0, X -> icmp X, X
6876 if (CI->isZero()) {
6877 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6878 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6879 }
6880
6881 // (X+4) == X -> false.
6882 if (Pred == ICmpInst::ICMP_EQ)
6883 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6884
6885 // (X+4) != X -> true.
6886 if (Pred == ICmpInst::ICMP_NE)
6887 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006888
6889 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6890 bool isNUW = false, isNSW = false;
6891 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6892 isNUW = Add->hasNoUnsignedWrap();
6893 isNSW = Add->hasNoSignedWrap();
6894 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006895
6896 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6897 // so the values can never be equal. Similiarly for all other "or equals"
6898 // operators.
6899
6900 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6901 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6902 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6903 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006904 // If this is an NUW add, then this is always false.
6905 if (isNUW)
6906 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6907
Chris Lattner2799baf2009-12-21 03:19:28 +00006908 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6909 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6910 }
6911
6912 // (X+1) >u X --> X <u (0-1) --> X != 255
6913 // (X+2) >u X --> X <u (0-2) --> X <u 254
6914 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006915 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6916 // If this is an NUW add, then this is always true.
6917 if (isNUW)
6918 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006919 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006920 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006921
6922 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6923 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6924 APInt::getSignedMaxValue(BitWidth));
6925
6926 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6927 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6928 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6929 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6930 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6931 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006932 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6933 // If this is an NSW add, then we have two cases: if the constant is
6934 // positive, then this is always false, if negative, this is always true.
6935 if (isNSW) {
6936 bool isTrue = CI->getValue().isNegative();
6937 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6938 }
6939
Chris Lattner2799baf2009-12-21 03:19:28 +00006940 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006941 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006942
6943 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6944 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6945 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6946 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6947 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6948 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006949
6950 // If this is an NSW add, then we have two cases: if the constant is
6951 // positive, then this is always true, if negative, this is always false.
6952 if (isNSW) {
6953 bool isTrue = !CI->getValue().isNegative();
6954 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6955 }
6956
Chris Lattner2799baf2009-12-21 03:19:28 +00006957 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6958 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6959 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6960}
Chris Lattner562ef782007-06-20 23:46:26 +00006961
6962/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6963/// and CmpRHS are both known to be integer constants.
6964Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6965 ConstantInt *DivRHS) {
6966 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6967 const APInt &CmpRHSV = CmpRHS->getValue();
6968
6969 // FIXME: If the operand types don't match the type of the divide
6970 // then don't attempt this transform. The code below doesn't have the
6971 // logic to deal with a signed divide and an unsigned compare (and
6972 // vice versa). This is because (x /s C1) <s C2 produces different
6973 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6974 // (x /u C1) <u C2. Simply casting the operands and result won't
6975 // work. :( The if statement below tests that condition and bails
6976 // if it finds it.
6977 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00006978 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00006979 return 0;
6980 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006981 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006982 if (DivIsSigned && DivRHS->isAllOnesValue())
6983 return 0; // The overflow computation also screws up here
6984 if (DivRHS->isOne())
6985 return 0; // Not worth bothering, and eliminates some funny cases
6986 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006987
6988 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6989 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6990 // C2 (CI). By solving for X we can turn this into a range check
6991 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006992 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006993
6994 // Determine if the product overflows by seeing if the product is
6995 // not equal to the divide. Make sure we do the same kind of divide
6996 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006997 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6998 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006999
7000 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00007001 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00007002
Chris Lattner1dbfd482007-06-21 18:11:19 +00007003 // Figure out the interval that is being checked. For example, a comparison
7004 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
7005 // Compute this interval based on the constants involved and the signedness of
7006 // the compare/divide. This computes a half-open interval, keeping track of
7007 // whether either value in the interval overflows. After analysis each
7008 // overflow variable is set to 0 if it's corresponding bound variable is valid
7009 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7010 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00007011 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007012
Chris Lattner562ef782007-06-20 23:46:26 +00007013 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00007014 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00007015 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007016 HiOverflow = LoOverflow = ProdOV;
7017 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007018 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00007019 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007020 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007021 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00007022 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00007023 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00007024 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007025 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
7026 HiOverflow = LoOverflow = ProdOV;
7027 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007028 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007029 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00007030 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007031 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00007032 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7033 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007034 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007035 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00007036 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00007037 true) ? -1 : 0;
7038 }
Chris Lattner562ef782007-06-20 23:46:26 +00007039 }
Dan Gohman76491272008-02-13 22:09:18 +00007040 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007041 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007042 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00007043 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007044 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007045 if (HiBound == DivRHS) { // -INTMIN = INTMIN
7046 HiOverflow = 1; // [INTMIN+1, overflow)
7047 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
7048 }
Dan Gohman76491272008-02-13 22:09:18 +00007049 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007050 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007051 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007052 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007053 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007054 LoOverflow = AddWithOverflow(LoBound, HiBound,
7055 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007056 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00007057 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
7058 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00007059 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007060 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007061 }
7062
Chris Lattner1dbfd482007-06-21 18:11:19 +00007063 // Dividing by a negative swaps the condition. LT <-> GT
7064 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00007065 }
7066
7067 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007068 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00007069 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00007070 case ICmpInst::ICMP_EQ:
7071 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007072 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007073 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007074 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007075 ICmpInst::ICMP_UGE, X, LoBound);
7076 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007077 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007078 ICmpInst::ICMP_ULT, X, HiBound);
7079 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007080 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007081 case ICmpInst::ICMP_NE:
7082 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007083 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007084 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007085 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007086 ICmpInst::ICMP_ULT, X, LoBound);
7087 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007088 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007089 ICmpInst::ICMP_UGE, X, HiBound);
7090 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007091 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007092 case ICmpInst::ICMP_ULT:
7093 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007094 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007095 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007096 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007097 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007098 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007099 case ICmpInst::ICMP_UGT:
7100 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007101 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007102 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007103 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007104 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007105 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007106 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007107 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007108 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007109 }
7110}
7111
7112
Chris Lattner01deb9d2007-04-03 17:43:25 +00007113/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7114///
7115Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7116 Instruction *LHSI,
7117 ConstantInt *RHS) {
7118 const APInt &RHSV = RHS->getValue();
7119
7120 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00007121 case Instruction::Trunc:
7122 if (ICI.isEquality() && LHSI->hasOneUse()) {
7123 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7124 // of the high bits truncated out of x are known.
7125 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7126 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7127 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7128 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7129 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7130
7131 // If all the high bits are known, we can do this xform.
7132 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7133 // Pull in the high bits from known-ones set.
7134 APInt NewRHS(RHS->getValue());
7135 NewRHS.zext(SrcBits);
7136 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007137 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007138 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00007139 }
7140 }
7141 break;
7142
Duncan Sands0091bf22007-04-04 06:42:45 +00007143 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00007144 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7145 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7146 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007147 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7148 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007149 Value *CompareVal = LHSI->getOperand(0);
7150
7151 // If the sign bit of the XorCST is not set, there is no change to
7152 // the operation, just stop using the Xor.
7153 if (!XorCST->getValue().isNegative()) {
7154 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00007155 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007156 return &ICI;
7157 }
7158
7159 // Was the old condition true if the operand is positive?
7160 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7161
7162 // If so, the new one isn't.
7163 isTrueIfPositive ^= true;
7164
7165 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007166 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007167 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007168 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007169 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007170 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007171 }
Nick Lewycky4333f492009-01-31 21:30:05 +00007172
7173 if (LHSI->hasOneUse()) {
7174 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7175 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7176 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007177 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007178 ? ICI.getUnsignedPredicate()
7179 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007180 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007181 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007182 }
7183
7184 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007185 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007186 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007187 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007188 ? ICI.getUnsignedPredicate()
7189 : ICI.getSignedPredicate();
7190 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007191 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007192 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007193 }
7194 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007195 }
7196 break;
7197 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7198 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7199 LHSI->getOperand(0)->hasOneUse()) {
7200 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7201
7202 // If the LHS is an AND of a truncating cast, we can widen the
7203 // and/compare to be the input width without changing the value
7204 // produced, eliminating a cast.
7205 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7206 // We can do this transformation if either the AND constant does not
7207 // have its sign bit set or if it is an equality comparison.
7208 // Extending a relational comparison when we're checking the sign
7209 // bit would not work.
7210 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007211 (ICI.isEquality() ||
7212 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007213 uint32_t BitWidth =
7214 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7215 APInt NewCST = AndCST->getValue();
7216 NewCST.zext(BitWidth);
7217 APInt NewCI = RHSV;
7218 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007219 Value *NewAnd =
7220 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007221 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007222 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00007223 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007224 }
7225 }
7226
7227 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7228 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7229 // happens a LOT in code produced by the C front-end, for bitfield
7230 // access.
7231 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7232 if (Shift && !Shift->isShift())
7233 Shift = 0;
7234
7235 ConstantInt *ShAmt;
7236 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7237 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7238 const Type *AndTy = AndCST->getType(); // Type of the and.
7239
7240 // We can fold this as long as we can't shift unknown bits
7241 // into the mask. This can only happen with signed shift
7242 // rights, as they sign-extend.
7243 if (ShAmt) {
7244 bool CanFold = Shift->isLogicalShift();
7245 if (!CanFold) {
7246 // To test for the bad case of the signed shr, see if any
7247 // of the bits shifted in could be tested after the mask.
7248 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7249 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7250
7251 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7252 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7253 AndCST->getValue()) == 0)
7254 CanFold = true;
7255 }
7256
7257 if (CanFold) {
7258 Constant *NewCst;
7259 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007260 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007261 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007262 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007263
7264 // Check to see if we are shifting out any of the bits being
7265 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007266 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007267 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007268 // If we shifted bits out, the fold is not going to work out.
7269 // As a special case, check to see if this means that the
7270 // result is always true or false now.
7271 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007272 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007273 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007274 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007275 } else {
7276 ICI.setOperand(1, NewCst);
7277 Constant *NewAndCST;
7278 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007279 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007280 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007281 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007282 LHSI->setOperand(1, NewAndCST);
7283 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007284 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007285 return &ICI;
7286 }
7287 }
7288 }
7289
7290 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7291 // preferable because it allows the C<<Y expression to be hoisted out
7292 // of a loop if Y is invariant and X is not.
7293 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007294 ICI.isEquality() && !Shift->isArithmeticShift() &&
7295 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007296 // Compute C << Y.
7297 Value *NS;
7298 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007299 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007300 } else {
7301 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007302 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007303 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007304
7305 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007306 Value *NewAnd =
7307 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007308
7309 ICI.setOperand(0, NewAnd);
7310 return &ICI;
7311 }
7312 }
7313 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00007314
7315 case Instruction::Or: {
7316 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7317 break;
7318 Value *P, *Q;
7319 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7320 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7321 // -> and (icmp eq P, null), (icmp eq Q, null).
7322
7323 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7324 Constant::getNullValue(P->getType()));
7325 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7326 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007327 Instruction *Op;
7328 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7329 Op = BinaryOperator::CreateAnd(ICIP, ICIQ, "");
7330 else
7331 Op = BinaryOperator::CreateOr(ICIP, ICIQ, "");
7332 Op->takeName(&ICI);
7333 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00007334 }
7335 break;
7336 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007337
Chris Lattnera0141b92007-07-15 20:42:37 +00007338 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7339 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7340 if (!ShAmt) break;
7341
7342 uint32_t TypeBits = RHSV.getBitWidth();
7343
7344 // Check that the shift amount is in range. If not, don't perform
7345 // undefined shifts. When the shift is visited it will be
7346 // simplified.
7347 if (ShAmt->uge(TypeBits))
7348 break;
7349
7350 if (ICI.isEquality()) {
7351 // If we are comparing against bits always shifted out, the
7352 // comparison cannot succeed.
7353 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007354 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007355 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007356 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7357 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007358 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007359 return ReplaceInstUsesWith(ICI, Cst);
7360 }
7361
7362 if (LHSI->hasOneUse()) {
7363 // Otherwise strength reduce the shift into an and.
7364 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7365 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007366 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007367 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007368
Chris Lattner74381062009-08-30 07:44:24 +00007369 Value *And =
7370 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007371 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007372 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007373 }
7374 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007375
7376 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7377 bool TrueIfSigned = false;
7378 if (LHSI->hasOneUse() &&
7379 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7380 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007381 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007382 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007383 Value *And =
7384 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007385 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007386 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007387 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007388 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007389 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007390
7391 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007392 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007393 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007394 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007395 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007396
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007397 // Check that the shift amount is in range. If not, don't perform
7398 // undefined shifts. When the shift is visited it will be
7399 // simplified.
7400 uint32_t TypeBits = RHSV.getBitWidth();
7401 if (ShAmt->uge(TypeBits))
7402 break;
7403
7404 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007405
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007406 // If we are comparing against bits always shifted out, the
7407 // comparison cannot succeed.
7408 APInt Comp = RHSV << ShAmtVal;
7409 if (LHSI->getOpcode() == Instruction::LShr)
7410 Comp = Comp.lshr(ShAmtVal);
7411 else
7412 Comp = Comp.ashr(ShAmtVal);
7413
7414 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7415 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007416 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007417 return ReplaceInstUsesWith(ICI, Cst);
7418 }
7419
7420 // Otherwise, check to see if the bits shifted out are known to be zero.
7421 // If so, we can compare against the unshifted value:
7422 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007423 if (LHSI->hasOneUse() &&
7424 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007425 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007426 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007427 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007428 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007429
Evan Chengf30752c2008-04-23 00:38:06 +00007430 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007431 // Otherwise strength reduce the shift into an and.
7432 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007433 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007434
Chris Lattner74381062009-08-30 07:44:24 +00007435 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7436 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007437 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007438 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007439 }
7440 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007441 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007442
7443 case Instruction::SDiv:
7444 case Instruction::UDiv:
7445 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7446 // Fold this div into the comparison, producing a range check.
7447 // Determine, based on the divide type, what the range is being
7448 // checked. If there is an overflow on the low or high side, remember
7449 // it, otherwise compute the range [low, hi) bounding the new value.
7450 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007451 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7452 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7453 DivRHS))
7454 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007455 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007456
7457 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007458 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007459 if (!ICI.isEquality()) {
7460 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7461 if (!LHSC) break;
7462 const APInt &LHSV = LHSC->getValue();
7463
7464 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7465 .subtract(LHSV);
7466
Nick Lewycky4a134af2009-10-25 05:20:17 +00007467 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007468 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007469 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007470 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007471 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007472 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007473 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007474 }
7475 } else {
7476 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007477 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007478 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007479 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007480 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007481 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007482 }
7483 }
7484 }
7485 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007486 }
7487
7488 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7489 if (ICI.isEquality()) {
7490 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7491
7492 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7493 // the second operand is a constant, simplify a bit.
7494 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7495 switch (BO->getOpcode()) {
7496 case Instruction::SRem:
7497 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7498 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7499 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7500 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007501 Value *NewRem =
7502 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7503 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007504 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007505 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007506 }
7507 }
7508 break;
7509 case Instruction::Add:
7510 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7511 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7512 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007513 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007514 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007515 } else if (RHSV == 0) {
7516 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7517 // efficiently invertible, or if the add has just this one use.
7518 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7519
Dan Gohman186a6362009-08-12 16:04:34 +00007520 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007521 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007522 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007523 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007524 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007525 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007526 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007527 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007528 }
7529 }
7530 break;
7531 case Instruction::Xor:
7532 // For the xor case, we can xor two constants together, eliminating
7533 // the explicit xor.
7534 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007535 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007536 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007537
7538 // FALLTHROUGH
7539 case Instruction::Sub:
7540 // Replace (([sub|xor] A, B) != 0) with (A != B)
7541 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007542 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007543 BO->getOperand(1));
7544 break;
7545
7546 case Instruction::Or:
7547 // If bits are being or'd in that are not present in the constant we
7548 // are comparing against, then the comparison could never succeed!
7549 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007550 Constant *NotCI = ConstantExpr::getNot(RHS);
7551 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007552 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007553 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007554 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007555 }
7556 break;
7557
7558 case Instruction::And:
7559 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7560 // If bits are being compared against that are and'd out, then the
7561 // comparison can never succeed!
7562 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007563 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007564 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007565 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007566
7567 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7568 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007569 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007570 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007571 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007572
7573 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007574 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007575 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007576 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007577 ICmpInst::Predicate pred = isICMP_NE ?
7578 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007579 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007580 }
7581
7582 // ((X & ~7) == 0) --> X < 8
7583 if (RHSV == 0 && isHighOnes(BOC)) {
7584 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007585 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007586 ICmpInst::Predicate pred = isICMP_NE ?
7587 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007588 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007589 }
7590 }
7591 default: break;
7592 }
7593 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7594 // Handle icmp {eq|ne} <intrinsic>, intcst.
7595 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007596 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007597 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007598 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007599 return &ICI;
7600 }
7601 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007602 }
7603 return 0;
7604}
7605
7606/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7607/// We only handle extending casts so far.
7608///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007609Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7610 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007611 Value *LHSCIOp = LHSCI->getOperand(0);
7612 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007613 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007614 Value *RHSCIOp;
7615
Chris Lattner8c756c12007-05-05 22:41:33 +00007616 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7617 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007618 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7619 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007620 cast<IntegerType>(DestTy)->getBitWidth()) {
7621 Value *RHSOp = 0;
7622 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007623 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007624 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7625 RHSOp = RHSC->getOperand(0);
7626 // If the pointer types don't match, insert a bitcast.
7627 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007628 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007629 }
7630
7631 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007632 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007633 }
7634
7635 // The code below only handles extension cast instructions, so far.
7636 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007637 if (LHSCI->getOpcode() != Instruction::ZExt &&
7638 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007639 return 0;
7640
Reid Spencere4d87aa2006-12-23 06:05:41 +00007641 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007642 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007643
Reid Spencere4d87aa2006-12-23 06:05:41 +00007644 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007645 // Not an extension from the same type?
7646 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007647 if (RHSCIOp->getType() != LHSCIOp->getType())
7648 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007649
Nick Lewycky4189a532008-01-28 03:48:02 +00007650 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007651 // and the other is a zext), then we can't handle this.
7652 if (CI->getOpcode() != LHSCI->getOpcode())
7653 return 0;
7654
Nick Lewycky4189a532008-01-28 03:48:02 +00007655 // Deal with equality cases early.
7656 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007657 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007658
7659 // A signed comparison of sign extended values simplifies into a
7660 // signed comparison.
7661 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007662 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007663
7664 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007665 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007666 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007667
Reid Spencere4d87aa2006-12-23 06:05:41 +00007668 // If we aren't dealing with a constant on the RHS, exit early
7669 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7670 if (!CI)
7671 return 0;
7672
7673 // Compute the constant that would happen if we truncated to SrcTy then
7674 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007675 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7676 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007677 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007678
7679 // If the re-extended constant didn't change...
7680 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007681 // Deal with equality cases early.
7682 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007683 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007684
7685 // A signed comparison of sign extended values simplifies into a
7686 // signed comparison.
7687 if (isSignedExt && isSignedCmp)
7688 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7689
7690 // The other three cases all fold into an unsigned comparison.
7691 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007692 }
7693
7694 // The re-extended constant changed so the constant cannot be represented
7695 // in the shorter type. Consequently, we cannot emit a simple comparison.
7696
7697 // First, handle some easy cases. We know the result cannot be equal at this
7698 // point so handle the ICI.isEquality() cases
7699 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007700 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007701 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007702 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007703
7704 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7705 // should have been folded away previously and not enter in here.
7706 Value *Result;
7707 if (isSignedCmp) {
7708 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007709 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007710 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007711 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007712 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007713 } else {
7714 // We're performing an unsigned comparison.
7715 if (isSignedExt) {
7716 // We're performing an unsigned comp with a sign extended value.
7717 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007718 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007719 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007720 } else {
7721 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007722 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007723 }
7724 }
7725
7726 // Finally, return the value computed.
7727 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007728 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007729 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007730
7731 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7732 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7733 "ICmp should be folded!");
7734 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007735 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007736 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007737}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007738
Reid Spencer832254e2007-02-02 02:16:23 +00007739Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7740 return commonShiftTransforms(I);
7741}
7742
7743Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7744 return commonShiftTransforms(I);
7745}
7746
7747Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007748 if (Instruction *R = commonShiftTransforms(I))
7749 return R;
7750
7751 Value *Op0 = I.getOperand(0);
7752
7753 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7754 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7755 if (CSI->isAllOnesValue())
7756 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007757
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007758 // See if we can turn a signed shr into an unsigned shr.
7759 if (MaskedValueIsZero(Op0,
7760 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7761 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7762
7763 // Arithmetic shifting an all-sign-bit value is a no-op.
7764 unsigned NumSignBits = ComputeNumSignBits(Op0);
7765 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7766 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007767
Chris Lattner348f6652007-12-06 01:59:46 +00007768 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007769}
7770
7771Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7772 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007773 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007774
7775 // shl X, 0 == X and shr X, 0 == X
7776 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007777 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7778 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007779 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007780
Reid Spencere4d87aa2006-12-23 06:05:41 +00007781 if (isa<UndefValue>(Op0)) {
7782 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007783 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007784 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007785 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007786 }
7787 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007788 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7789 return ReplaceInstUsesWith(I, Op0);
7790 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007791 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007792 }
7793
Dan Gohman9004c8a2009-05-21 02:28:33 +00007794 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007795 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007796 return &I;
7797
Chris Lattner2eefe512004-04-09 19:05:30 +00007798 // Try to fold constant and into select arguments.
7799 if (isa<Constant>(Op0))
7800 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007801 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007802 return R;
7803
Reid Spencerb83eb642006-10-20 07:07:24 +00007804 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007805 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7806 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007807 return 0;
7808}
7809
Reid Spencerb83eb642006-10-20 07:07:24 +00007810Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007811 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007812 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007813
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007814 // See if we can simplify any instructions used by the instruction whose sole
7815 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007816 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007817
Dan Gohmana119de82009-06-14 23:30:43 +00007818 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7819 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007820 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007821 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007822 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007823 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007824 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007825 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007826 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007827 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007828 }
7829
7830 // ((X*C1) << C2) == (X * (C1 << C2))
7831 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7832 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7833 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007834 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007835 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007836
7837 // Try to fold constant and into select arguments.
7838 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7839 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7840 return R;
7841 if (isa<PHINode>(Op0))
7842 if (Instruction *NV = FoldOpIntoPhi(I))
7843 return NV;
7844
Chris Lattner8999dd32007-12-22 09:07:47 +00007845 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7846 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7847 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7848 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7849 // place. Don't try to do this transformation in this case. Also, we
7850 // require that the input operand is a shift-by-constant so that we have
7851 // confidence that the shifts will get folded together. We could do this
7852 // xform in more cases, but it is unlikely to be profitable.
7853 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7854 isa<ConstantInt>(TrOp->getOperand(1))) {
7855 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007856 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007857 // (shift2 (shift1 & 0x00FF), c2)
7858 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007859
7860 // For logical shifts, the truncation has the effect of making the high
7861 // part of the register be zeros. Emulate this by inserting an AND to
7862 // clear the top bits as needed. This 'and' will usually be zapped by
7863 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007864 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7865 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007866 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7867
7868 // The mask we constructed says what the trunc would do if occurring
7869 // between the shifts. We want to know the effect *after* the second
7870 // shift. We know that it is a logical shift by a constant, so adjust the
7871 // mask as appropriate.
7872 if (I.getOpcode() == Instruction::Shl)
7873 MaskV <<= Op1->getZExtValue();
7874 else {
7875 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7876 MaskV = MaskV.lshr(Op1->getZExtValue());
7877 }
7878
Chris Lattner74381062009-08-30 07:44:24 +00007879 // shift1 & 0x00FF
7880 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7881 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007882
7883 // Return the value truncated to the interesting size.
7884 return new TruncInst(And, I.getType());
7885 }
7886 }
7887
Chris Lattner4d5542c2006-01-06 07:12:35 +00007888 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007889 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7890 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7891 Value *V1, *V2;
7892 ConstantInt *CC;
7893 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007894 default: break;
7895 case Instruction::Add:
7896 case Instruction::And:
7897 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007898 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007899 // These operators commute.
7900 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007901 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007902 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007903 m_Specific(Op1)))) {
7904 Value *YS = // (Y << C)
7905 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7906 // (X + (Y << C))
7907 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7908 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007909 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007910 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007911 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007912 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007913
Chris Lattner150f12a2005-09-18 06:30:59 +00007914 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007915 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007916 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007917 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007918 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007919 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007920 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007921 Value *YS = // (Y << C)
7922 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7923 Op0BO->getName());
7924 // X & (CC << C)
7925 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7926 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007927 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007928 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007929 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007930
Reid Spencera07cb7d2007-02-02 14:41:37 +00007931 // FALL THROUGH.
7932 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007933 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007934 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007935 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007936 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007937 Value *YS = // (Y << C)
7938 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7939 // (X + (Y << C))
7940 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7941 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007942 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007943 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007944 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007945 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007946
Chris Lattner13d4ab42006-05-31 21:14:00 +00007947 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007948 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7949 match(Op0BO->getOperand(0),
7950 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007951 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007952 cast<BinaryOperator>(Op0BO->getOperand(0))
7953 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007954 Value *YS = // (Y << C)
7955 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7956 // X & (CC << C)
7957 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7958 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007959
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007960 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007961 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007962
Chris Lattner11021cb2005-09-18 05:12:10 +00007963 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007964 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007965 }
7966
7967
7968 // If the operand is an bitwise operator with a constant RHS, and the
7969 // shift is the only use, we can pull it out of the shift.
7970 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7971 bool isValid = true; // Valid only for And, Or, Xor
7972 bool highBitSet = false; // Transform if high bit of constant set?
7973
7974 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007975 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007976 case Instruction::Add:
7977 isValid = isLeftShift;
7978 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007979 case Instruction::Or:
7980 case Instruction::Xor:
7981 highBitSet = false;
7982 break;
7983 case Instruction::And:
7984 highBitSet = true;
7985 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007986 }
7987
7988 // If this is a signed shift right, and the high bit is modified
7989 // by the logical operation, do not perform the transformation.
7990 // The highBitSet boolean indicates the value of the high bit of
7991 // the constant which would cause it to be modified for this
7992 // operation.
7993 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007994 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007995 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007996
7997 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007998 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007999
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008000 Value *NewShift =
8001 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00008002 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008003
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008004 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00008005 NewRHS);
8006 }
8007 }
8008 }
8009 }
8010
Chris Lattnerad0124c2006-01-06 07:52:12 +00008011 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00008012 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8013 if (ShiftOp && !ShiftOp->isShift())
8014 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008015
Reid Spencerb83eb642006-10-20 07:07:24 +00008016 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008017 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008018 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8019 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008020 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8021 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
8022 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00008023
Zhou Sheng4351c642007-04-02 08:20:41 +00008024 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00008025
8026 const IntegerType *Ty = cast<IntegerType>(I.getType());
8027
8028 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00008029 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008030 // If this is oversized composite shift, then unsigned shifts get 0, ashr
8031 // saturates.
8032 if (AmtSum >= TypeBits) {
8033 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00008034 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008035 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
8036 }
8037
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008038 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00008039 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008040 }
8041
8042 if (ShiftOp->getOpcode() == Instruction::LShr &&
8043 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008044 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00008045 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008046
Chris Lattnerb87056f2007-02-05 00:57:54 +00008047 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00008048 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008049 }
8050
8051 if (ShiftOp->getOpcode() == Instruction::AShr &&
8052 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00008053 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00008054 if (AmtSum >= TypeBits)
8055 AmtSum = TypeBits-1;
8056
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008057 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008058
Zhou Shenge9e03f62007-03-28 15:02:20 +00008059 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008060 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008061 }
8062
Chris Lattnerb87056f2007-02-05 00:57:54 +00008063 // Okay, if we get here, one shift must be left, and the other shift must be
8064 // right. See if the amounts are equal.
8065 if (ShiftAmt1 == ShiftAmt2) {
8066 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8067 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00008068 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008069 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008070 }
8071 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8072 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00008073 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008074 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008075 }
8076 // We can simplify ((X << C) >>s C) into a trunc + sext.
8077 // NOTE: we could do this for any C, but that would make 'unusual' integer
8078 // types. For now, just stick to ones well-supported by the code
8079 // generators.
8080 const Type *SExtType = 0;
8081 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00008082 case 1 :
8083 case 8 :
8084 case 16 :
8085 case 32 :
8086 case 64 :
8087 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00008088 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00008089 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008090 default: break;
8091 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008092 if (SExtType)
8093 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008094 // Otherwise, we can't handle it yet.
8095 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00008096 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008097
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008098 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008099 if (I.getOpcode() == Instruction::Shl) {
8100 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8101 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008102 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00008103
Reid Spencer55702aa2007-03-25 21:11:44 +00008104 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008105 return BinaryOperator::CreateAnd(Shift,
8106 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008107 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008108
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008109 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008110 if (I.getOpcode() == Instruction::LShr) {
8111 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008112 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008113
Reid Spencerd5e30f02007-03-26 17:18:58 +00008114 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008115 return BinaryOperator::CreateAnd(Shift,
8116 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00008117 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008118
8119 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8120 } else {
8121 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00008122 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008123
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008124 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008125 if (I.getOpcode() == Instruction::Shl) {
8126 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8127 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008128 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8129 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008130
Reid Spencer55702aa2007-03-25 21:11:44 +00008131 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008132 return BinaryOperator::CreateAnd(Shift,
8133 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008134 }
8135
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008136 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008137 if (I.getOpcode() == Instruction::LShr) {
8138 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008139 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008140
Reid Spencer68d27cf2007-03-26 23:45:51 +00008141 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008142 return BinaryOperator::CreateAnd(Shift,
8143 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008144 }
8145
8146 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008147 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00008148 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00008149 return 0;
8150}
8151
Chris Lattnera1be5662002-05-02 17:06:02 +00008152
Chris Lattnercfd65102005-10-29 04:36:15 +00008153/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8154/// expression. If so, decompose it, returning some value X, such that Val is
8155/// X*Scale+Offset.
8156///
8157static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008158 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008159 assert(Val->getType() == Type::getInt32Ty(*Context) &&
8160 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00008161 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008162 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00008163 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00008164 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00008165 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8166 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8167 if (I->getOpcode() == Instruction::Shl) {
8168 // This is a value scaled by '1 << the shift amt'.
8169 Scale = 1U << RHS->getZExtValue();
8170 Offset = 0;
8171 return I->getOperand(0);
8172 } else if (I->getOpcode() == Instruction::Mul) {
8173 // This value is scaled by 'RHS'.
8174 Scale = RHS->getZExtValue();
8175 Offset = 0;
8176 return I->getOperand(0);
8177 } else if (I->getOpcode() == Instruction::Add) {
8178 // We have X+C. Check to see if we really have (X*C2)+C1,
8179 // where C1 is divisible by C2.
8180 unsigned SubScale;
8181 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00008182 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8183 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00008184 Offset += RHS->getZExtValue();
8185 Scale = SubScale;
8186 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00008187 }
8188 }
8189 }
8190
8191 // Otherwise, we can't look past this.
8192 Scale = 1;
8193 Offset = 0;
8194 return Val;
8195}
8196
8197
Chris Lattnerb3f83972005-10-24 06:03:58 +00008198/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8199/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008200Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00008201 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008202 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00008203
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008204 BuilderTy AllocaBuilder(*Builder);
8205 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8206
Chris Lattnerb53c2382005-10-24 06:22:12 +00008207 // Remove any uses of AI that are dead.
8208 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008209
Chris Lattnerb53c2382005-10-24 06:22:12 +00008210 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8211 Instruction *User = cast<Instruction>(*UI++);
8212 if (isInstructionTriviallyDead(User)) {
8213 while (UI != E && *UI == User)
8214 ++UI; // If this instruction uses AI more than once, don't break UI.
8215
Chris Lattnerb53c2382005-10-24 06:22:12 +00008216 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008217 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008218 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008219 }
8220 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008221
8222 // This requires TargetData to get the alloca alignment and size information.
8223 if (!TD) return 0;
8224
Chris Lattnerb3f83972005-10-24 06:03:58 +00008225 // Get the type really allocated and the type casted to.
8226 const Type *AllocElTy = AI.getAllocatedType();
8227 const Type *CastElTy = PTy->getElementType();
8228 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008229
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008230 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8231 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008232 if (CastElTyAlign < AllocElTyAlign) return 0;
8233
Chris Lattner39387a52005-10-24 06:35:18 +00008234 // If the allocation has multiple uses, only promote it if we are strictly
8235 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008236 // same, we open the door to infinite loops of various kinds. (A reference
8237 // from a dbg.declare doesn't count as a use for this purpose.)
8238 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8239 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008240
Duncan Sands777d2302009-05-09 07:06:46 +00008241 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8242 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008243 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008244
Chris Lattner455fcc82005-10-29 03:19:53 +00008245 // See if we can satisfy the modulus by pulling a scale out of the array
8246 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008247 unsigned ArraySizeScale;
8248 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008249 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00008250 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8251 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00008252
Chris Lattner455fcc82005-10-29 03:19:53 +00008253 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8254 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008255 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8256 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008257
Chris Lattner455fcc82005-10-29 03:19:53 +00008258 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8259 Value *Amt = 0;
8260 if (Scale == 1) {
8261 Amt = NumElements;
8262 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00008263 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008264 // Insert before the alloca, not before the cast.
8265 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008266 }
8267
Jeff Cohen86796be2007-04-04 16:58:57 +00008268 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008269 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008270 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008271 }
8272
Victor Hernandez7b929da2009-10-23 21:09:37 +00008273 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008274 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008275 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008276
Dale Johannesena0a66372009-03-05 00:39:02 +00008277 // If the allocation has one real use plus a dbg.declare, just remove the
8278 // declare.
8279 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8280 EraseInstFromFunction(*DI);
8281 }
8282 // If the allocation has multiple real uses, insert a cast and change all
8283 // things that used it to use the new cast. This will also hack on CI, but it
8284 // will die soon.
8285 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008286 // New is the allocation instruction, pointer typed. AI is the original
8287 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008288 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008289 AI.replaceAllUsesWith(NewCast);
8290 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008291 return ReplaceInstUsesWith(CI, New);
8292}
8293
Chris Lattner70074e02006-05-13 02:06:03 +00008294/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008295/// and return it as type Ty without inserting any new casts and without
8296/// changing the computed value. This is used by code that tries to decide
8297/// whether promoting or shrinking integer operations to wider or smaller types
8298/// will allow us to eliminate a truncate or extend.
8299///
8300/// This is a truncation operation if Ty is smaller than V->getType(), or an
8301/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008302///
8303/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8304/// should return true if trunc(V) can be computed by computing V in the smaller
8305/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8306/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8307/// efficiently truncated.
8308///
8309/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8310/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8311/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008312bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008313 unsigned CastOpc,
8314 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008315 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008316 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008317 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008318
8319 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008320 if (!I) return false;
8321
Dan Gohman6de29f82009-06-15 22:12:54 +00008322 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008323
Chris Lattner951626b2007-08-02 06:11:14 +00008324 // If this is an extension or truncate, we can often eliminate it.
8325 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8326 // If this is a cast from the destination type, we can trivially eliminate
8327 // it, and this will remove a cast overall.
8328 if (I->getOperand(0)->getType() == Ty) {
8329 // If the first operand is itself a cast, and is eliminable, do not count
8330 // this as an eliminable cast. We would prefer to eliminate those two
8331 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008332 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008333 ++NumCastsRemoved;
8334 return true;
8335 }
8336 }
8337
8338 // We can't extend or shrink something that has multiple uses: doing so would
8339 // require duplicating the instruction in general, which isn't profitable.
8340 if (!I->hasOneUse()) return false;
8341
Evan Chengf35fd542009-01-15 17:01:23 +00008342 unsigned Opc = I->getOpcode();
8343 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008344 case Instruction::Add:
8345 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008346 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008347 case Instruction::And:
8348 case Instruction::Or:
8349 case Instruction::Xor:
8350 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008351 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008352 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008353 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008354 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008355
Eli Friedman070a9812009-07-13 22:46:01 +00008356 case Instruction::UDiv:
8357 case Instruction::URem: {
8358 // UDiv and URem can be truncated if all the truncated bits are zero.
8359 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8360 uint32_t BitWidth = Ty->getScalarSizeInBits();
8361 if (BitWidth < OrigBitWidth) {
8362 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8363 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8364 MaskedValueIsZero(I->getOperand(1), Mask)) {
8365 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8366 NumCastsRemoved) &&
8367 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8368 NumCastsRemoved);
8369 }
8370 }
8371 break;
8372 }
Chris Lattner46b96052006-11-29 07:18:39 +00008373 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008374 // If we are truncating the result of this SHL, and if it's a shift of a
8375 // constant amount, we can always perform a SHL in a smaller type.
8376 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008377 uint32_t BitWidth = Ty->getScalarSizeInBits();
8378 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008379 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008380 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008381 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008382 }
8383 break;
8384 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008385 // If this is a truncate of a logical shr, we can truncate it to a smaller
8386 // lshr iff we know that the bits we would otherwise be shifting in are
8387 // already zeros.
8388 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008389 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8390 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008391 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008392 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008393 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8394 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008395 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008396 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008397 }
8398 }
Chris Lattner46b96052006-11-29 07:18:39 +00008399 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008400 case Instruction::ZExt:
8401 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008402 case Instruction::Trunc:
8403 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008404 // can safely replace it. Note that replacing it does not reduce the number
8405 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008406 if (Opc == CastOpc)
8407 return true;
8408
8409 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008410 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008411 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008412 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008413 case Instruction::Select: {
8414 SelectInst *SI = cast<SelectInst>(I);
8415 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008416 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008417 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008418 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008419 }
Chris Lattner8114b712008-06-18 04:00:49 +00008420 case Instruction::PHI: {
8421 // We can change a phi if we can change all operands.
8422 PHINode *PN = cast<PHINode>(I);
8423 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8424 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008425 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008426 return false;
8427 return true;
8428 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008429 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008430 // TODO: Can handle more cases here.
8431 break;
8432 }
8433
8434 return false;
8435}
8436
8437/// EvaluateInDifferentType - Given an expression that
8438/// CanEvaluateInDifferentType returns true for, actually insert the code to
8439/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008440Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008441 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008442 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008443 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008444
8445 // Otherwise, it must be an instruction.
8446 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008447 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008448 unsigned Opc = I->getOpcode();
8449 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008450 case Instruction::Add:
8451 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008452 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008453 case Instruction::And:
8454 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008455 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008456 case Instruction::AShr:
8457 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008458 case Instruction::Shl:
8459 case Instruction::UDiv:
8460 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008461 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008462 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008463 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008464 break;
8465 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008466 case Instruction::Trunc:
8467 case Instruction::ZExt:
8468 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008469 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008470 // just return the source. There's no need to insert it because it is not
8471 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008472 if (I->getOperand(0)->getType() == Ty)
8473 return I->getOperand(0);
8474
Chris Lattner8114b712008-06-18 04:00:49 +00008475 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008476 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008477 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008478 case Instruction::Select: {
8479 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8480 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8481 Res = SelectInst::Create(I->getOperand(0), True, False);
8482 break;
8483 }
Chris Lattner8114b712008-06-18 04:00:49 +00008484 case Instruction::PHI: {
8485 PHINode *OPN = cast<PHINode>(I);
8486 PHINode *NPN = PHINode::Create(Ty);
8487 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8488 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8489 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8490 }
8491 Res = NPN;
8492 break;
8493 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008494 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008495 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008496 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008497 break;
8498 }
8499
Chris Lattner8114b712008-06-18 04:00:49 +00008500 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008501 return InsertNewInstBefore(Res, *I);
8502}
8503
Reid Spencer3da59db2006-11-27 01:05:10 +00008504/// @brief Implement the transforms common to all CastInst visitors.
8505Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008506 Value *Src = CI.getOperand(0);
8507
Dan Gohman23d9d272007-05-11 21:10:54 +00008508 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008509 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008510 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008511 if (Instruction::CastOps opc =
8512 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8513 // The first cast (CSrc) is eliminable so we need to fix up or replace
8514 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008515 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008516 }
8517 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008518
Reid Spencer3da59db2006-11-27 01:05:10 +00008519 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008520 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8521 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8522 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008523
8524 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008525 if (isa<PHINode>(Src)) {
8526 // We don't do this if this would create a PHI node with an illegal type if
8527 // it is currently legal.
8528 if (!isa<IntegerType>(Src->getType()) ||
8529 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008530 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008531 if (Instruction *NV = FoldOpIntoPhi(CI))
8532 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008533 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008534
Reid Spencer3da59db2006-11-27 01:05:10 +00008535 return 0;
8536}
8537
Chris Lattner46cd5a12009-01-09 05:44:56 +00008538/// FindElementAtOffset - Given a type and a constant offset, determine whether
8539/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008540/// the specified offset. If so, fill them into NewIndices and return the
8541/// resultant element type, otherwise return null.
8542static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8543 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008544 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008545 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008546 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008547 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008548
8549 // Start with the index over the outer type. Note that the type size
8550 // might be zero (even if the offset isn't zero) if the indexed type
8551 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008552 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008553 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008554 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008555 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008556 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008557
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008558 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008559 if (Offset < 0) {
8560 --FirstIdx;
8561 Offset += TySize;
8562 assert(Offset >= 0);
8563 }
8564 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8565 }
8566
Owen Andersoneed707b2009-07-24 23:12:02 +00008567 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008568
8569 // Index into the types. If we fail, set OrigBase to null.
8570 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008571 // Indexing into tail padding between struct/array elements.
8572 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008573 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008574
Chris Lattner46cd5a12009-01-09 05:44:56 +00008575 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8576 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008577 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8578 "Offset must stay within the indexed type");
8579
Chris Lattner46cd5a12009-01-09 05:44:56 +00008580 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008581 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008582
8583 Offset -= SL->getElementOffset(Elt);
8584 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008585 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008586 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008587 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008588 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008589 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008590 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008591 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008592 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008593 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008594 }
8595 }
8596
Chris Lattner3914f722009-01-24 01:00:13 +00008597 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008598}
8599
Chris Lattnerd3e28342007-04-27 17:44:50 +00008600/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8601Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8602 Value *Src = CI.getOperand(0);
8603
Chris Lattnerd3e28342007-04-27 17:44:50 +00008604 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008605 // If casting the result of a getelementptr instruction with no offset, turn
8606 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008607 if (GEP->hasAllZeroIndices()) {
8608 // Changing the cast operand is usually not a good idea but it is safe
8609 // here because the pointer operand is being replaced with another
8610 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008611 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008612 CI.setOperand(0, GEP->getOperand(0));
8613 return &CI;
8614 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008615
8616 // If the GEP has a single use, and the base pointer is a bitcast, and the
8617 // GEP computes a constant offset, see if we can convert these three
8618 // instructions into fewer. This typically happens with unions and other
8619 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008620 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008621 if (GEP->hasAllConstantIndices()) {
8622 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008623 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008624 int64_t Offset = OffsetV->getSExtValue();
8625
8626 // Get the base pointer input of the bitcast, and the type it points to.
8627 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8628 const Type *GEPIdxTy =
8629 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008630 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008631 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008632 // If we were able to index down into an element, create the GEP
8633 // and bitcast the result. This eliminates one bitcast, potentially
8634 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008635 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8636 Builder->CreateInBoundsGEP(OrigBase,
8637 NewIndices.begin(), NewIndices.end()) :
8638 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008639 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008640
Chris Lattner46cd5a12009-01-09 05:44:56 +00008641 if (isa<BitCastInst>(CI))
8642 return new BitCastInst(NGEP, CI.getType());
8643 assert(isa<PtrToIntInst>(CI));
8644 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008645 }
8646 }
8647 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008648 }
8649
8650 return commonCastTransforms(CI);
8651}
8652
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008653/// commonIntCastTransforms - This function implements the common transforms
8654/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008655Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8656 if (Instruction *Result = commonCastTransforms(CI))
8657 return Result;
8658
8659 Value *Src = CI.getOperand(0);
8660 const Type *SrcTy = Src->getType();
8661 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008662 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8663 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008664
Reid Spencer3da59db2006-11-27 01:05:10 +00008665 // See if we can simplify any instructions used by the LHS whose sole
8666 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008667 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008668 return &CI;
8669
8670 // If the source isn't an instruction or has more than one use then we
8671 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008672 Instruction *SrcI = dyn_cast<Instruction>(Src);
8673 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008674 return 0;
8675
Chris Lattnerc739cd62007-03-03 05:27:34 +00008676 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008677 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008678 // Only do this if the dest type is a simple type, don't convert the
8679 // expression tree to something weird like i93 unless the source is also
8680 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008681 if ((isa<VectorType>(DestTy) ||
8682 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8683 CanEvaluateInDifferentType(SrcI, DestTy,
8684 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008685 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008686 // eliminates the cast, so it is always a win. If this is a zero-extension,
8687 // we need to do an AND to maintain the clear top-part of the computation,
8688 // so we require that the input have eliminated at least one cast. If this
8689 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008690 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008691 bool DoXForm = false;
8692 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008693 switch (CI.getOpcode()) {
8694 default:
8695 // All the others use floating point so we shouldn't actually
8696 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008697 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008698 case Instruction::Trunc:
8699 DoXForm = true;
8700 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008701 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008702 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008703
Chris Lattner39c27ed2009-01-31 19:05:27 +00008704 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008705 // If it's unnecessary to issue an AND to clear the high bits, it's
8706 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008707 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008708 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8709 if (MaskedValueIsZero(TryRes, Mask))
8710 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008711
8712 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008713 if (TryI->use_empty())
8714 EraseInstFromFunction(*TryI);
8715 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008716 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008717 }
Evan Chengf35fd542009-01-15 17:01:23 +00008718 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008719 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008720 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008721 // If we do not have to emit the truncate + sext pair, then it's always
8722 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008723 //
8724 // It's not safe to eliminate the trunc + sext pair if one of the
8725 // eliminated cast is a truncate. e.g.
8726 // t2 = trunc i32 t1 to i16
8727 // t3 = sext i16 t2 to i32
8728 // !=
8729 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008730 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008731 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8732 if (NumSignBits > (DestBitSize - SrcBitSize))
8733 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008734
8735 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008736 if (TryI->use_empty())
8737 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008738 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008739 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008740 }
Evan Chengf35fd542009-01-15 17:01:23 +00008741 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008742
8743 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008744 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8745 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008746 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8747 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008748 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008749 // Just replace this cast with the result.
8750 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008751
Reid Spencer3da59db2006-11-27 01:05:10 +00008752 assert(Res->getType() == DestTy);
8753 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008754 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008755 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008756 // Just replace this cast with the result.
8757 return ReplaceInstUsesWith(CI, Res);
8758 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008759 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008760
8761 // If the high bits are already zero, just replace this cast with the
8762 // result.
8763 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8764 if (MaskedValueIsZero(Res, Mask))
8765 return ReplaceInstUsesWith(CI, Res);
8766
8767 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008768 Constant *C = ConstantInt::get(*Context,
8769 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008770 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008771 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008772 case Instruction::SExt: {
8773 // If the high bits are already filled with sign bit, just replace this
8774 // cast with the result.
8775 unsigned NumSignBits = ComputeNumSignBits(Res);
8776 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008777 return ReplaceInstUsesWith(CI, Res);
8778
Reid Spencer3da59db2006-11-27 01:05:10 +00008779 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008780 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008781 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008782 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008783 }
8784 }
8785
8786 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8787 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8788
8789 switch (SrcI->getOpcode()) {
8790 case Instruction::Add:
8791 case Instruction::Mul:
8792 case Instruction::And:
8793 case Instruction::Or:
8794 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008795 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008796 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8797 // Don't insert two casts unless at least one can be eliminated.
8798 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008799 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008800 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8801 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008802 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008803 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008804 }
8805 }
8806
8807 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8808 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8809 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008810 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008811 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008812 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008813 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008814 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008815 }
8816 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008817
Eli Friedman65445c52009-07-13 21:45:57 +00008818 case Instruction::Shl: {
8819 // Canonicalize trunc inside shl, if we can.
8820 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8821 if (CI && DestBitSize < SrcBitSize &&
8822 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008823 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8824 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008825 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008826 }
8827 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008828 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008829 }
8830 return 0;
8831}
8832
Chris Lattner8a9f5712007-04-11 06:57:46 +00008833Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008834 if (Instruction *Result = commonIntCastTransforms(CI))
8835 return Result;
8836
8837 Value *Src = CI.getOperand(0);
8838 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008839 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8840 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008841
8842 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008843 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008844 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008845 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008846 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008847 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008848 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008849
Chris Lattner4f9797d2009-03-24 18:15:30 +00008850 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8851 ConstantInt *ShAmtV = 0;
8852 Value *ShiftOp = 0;
8853 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008854 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008855 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8856
8857 // Get a mask for the bits shifting in.
8858 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8859 if (MaskedValueIsZero(ShiftOp, Mask)) {
8860 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008861 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008862
8863 // Okay, we can shrink this. Truncate the input, then return a new
8864 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008865 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008866 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008867 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008868 }
8869 }
Chris Lattner9956c052009-11-08 19:23:30 +00008870
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008871 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008872}
8873
Evan Chengb98a10e2008-03-24 00:21:34 +00008874/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8875/// in order to eliminate the icmp.
8876Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8877 bool DoXform) {
8878 // If we are just checking for a icmp eq of a single bit and zext'ing it
8879 // to an integer, then shift the bit to the appropriate place and then
8880 // cast to integer to avoid the comparison.
8881 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8882 const APInt &Op1CV = Op1C->getValue();
8883
8884 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8885 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8886 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8887 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8888 if (!DoXform) return ICI;
8889
8890 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008891 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008892 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008893 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008894 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008895 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008896
8897 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008898 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008899 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008900 }
8901
8902 return ReplaceInstUsesWith(CI, In);
8903 }
8904
8905
8906
8907 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8908 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8909 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8910 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8911 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8912 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8913 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8914 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8915 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8916 // This only works for EQ and NE
8917 ICI->isEquality()) {
8918 // If Op1C some other power of two, convert:
8919 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8920 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8921 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8922 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8923
8924 APInt KnownZeroMask(~KnownZero);
8925 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8926 if (!DoXform) return ICI;
8927
8928 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8929 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8930 // (X&4) == 2 --> false
8931 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008932 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008933 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008934 return ReplaceInstUsesWith(CI, Res);
8935 }
8936
8937 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8938 Value *In = ICI->getOperand(0);
8939 if (ShiftAmt) {
8940 // Perform a logical shr by shiftamt.
8941 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008942 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8943 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008944 }
8945
8946 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008947 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008948 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008949 }
8950
8951 if (CI.getType() == In->getType())
8952 return ReplaceInstUsesWith(CI, In);
8953 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008954 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008955 }
8956 }
8957 }
8958
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008959 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
8960 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
8961 // may lead to additional simplifications.
8962 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
8963 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
8964 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008965 Value *LHS = ICI->getOperand(0);
8966 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008967
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008968 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
8969 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
8970 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8971 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
8972 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008973
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008974 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
8975 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
8976 APInt UnknownBit = ~KnownBits;
8977 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008978 if (!DoXform) return ICI;
8979
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008980 Value *Result = Builder->CreateXor(LHS, RHS);
8981
8982 // Mask off any bits that are set and won't be shifted away.
8983 if (KnownOneLHS.uge(UnknownBit))
8984 Result = Builder->CreateAnd(Result,
8985 ConstantInt::get(ITy, UnknownBit));
8986
8987 // Shift the bit we're testing down to the lsb.
8988 Result = Builder->CreateLShr(
8989 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
8990
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008991 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00008992 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
8993 Result->takeName(ICI);
8994 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00008995 }
8996 }
8997 }
8998 }
8999
Evan Chengb98a10e2008-03-24 00:21:34 +00009000 return 0;
9001}
9002
Chris Lattner8a9f5712007-04-11 06:57:46 +00009003Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009004 // If one of the common conversion will work ..
9005 if (Instruction *Result = commonIntCastTransforms(CI))
9006 return Result;
9007
9008 Value *Src = CI.getOperand(0);
9009
Chris Lattnera84f47c2009-02-17 20:47:23 +00009010 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9011 // types and if the sizes are just right we can convert this into a logical
9012 // 'and' which will be much cheaper than the pair of casts.
9013 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
9014 // Get the sizes of the types involved. We know that the intermediate type
9015 // will be smaller than A or C, but don't know the relation between A and C.
9016 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009017 unsigned SrcSize = A->getType()->getScalarSizeInBits();
9018 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9019 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00009020 // If we're actually extending zero bits, then if
9021 // SrcSize < DstSize: zext(a & mask)
9022 // SrcSize == DstSize: a & mask
9023 // SrcSize > DstSize: trunc(a) & mask
9024 if (SrcSize < DstSize) {
9025 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009026 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009027 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009028 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009029 }
9030
9031 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00009032 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009033 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009034 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009035 }
9036 if (SrcSize > DstSize) {
9037 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009038 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00009039 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00009040 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009041 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00009042 }
9043 }
9044
Evan Chengb98a10e2008-03-24 00:21:34 +00009045 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9046 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00009047
Evan Chengb98a10e2008-03-24 00:21:34 +00009048 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9049 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9050 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9051 // of the (zext icmp) will be transformed.
9052 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9053 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9054 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9055 (transformZExtICmp(LHS, CI, false) ||
9056 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009057 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9058 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009059 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00009060 }
Evan Chengb98a10e2008-03-24 00:21:34 +00009061 }
9062
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009063 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00009064 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9065 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9066 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9067 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009068 if (TI0->getType() == CI.getType())
9069 return
9070 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00009071 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00009072 }
9073
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009074 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9075 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9076 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9077 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9078 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9079 And->getOperand(1) == C)
9080 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9081 Value *TI0 = TI->getOperand(0);
9082 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009083 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009084 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009085 return BinaryOperator::CreateXor(NewAnd, ZC);
9086 }
9087 }
9088
Reid Spencer3da59db2006-11-27 01:05:10 +00009089 return 0;
9090}
9091
Chris Lattner8a9f5712007-04-11 06:57:46 +00009092Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00009093 if (Instruction *I = commonIntCastTransforms(CI))
9094 return I;
9095
Chris Lattner8a9f5712007-04-11 06:57:46 +00009096 Value *Src = CI.getOperand(0);
9097
Dan Gohman1975d032008-10-30 20:40:10 +00009098 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00009099 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00009100 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00009101 Constant::getAllOnesValue(CI.getType()),
9102 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00009103
9104 // See if the value being truncated is already sign extended. If so, just
9105 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00009106 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00009107 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009108 unsigned OpBits = Op->getType()->getScalarSizeInBits();
9109 unsigned MidBits = Src->getType()->getScalarSizeInBits();
9110 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00009111 unsigned NumSignBits = ComputeNumSignBits(Op);
9112
9113 if (OpBits == DestBits) {
9114 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9115 // bits, it is already ready.
9116 if (NumSignBits > DestBits-MidBits)
9117 return ReplaceInstUsesWith(CI, Op);
9118 } else if (OpBits < DestBits) {
9119 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9120 // bits, just sext from i32.
9121 if (NumSignBits > OpBits-MidBits)
9122 return new SExtInst(Op, CI.getType(), "tmp");
9123 } else {
9124 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9125 // bits, just truncate to i32.
9126 if (NumSignBits > OpBits-MidBits)
9127 return new TruncInst(Op, CI.getType(), "tmp");
9128 }
9129 }
Chris Lattner46bbad22008-08-06 07:35:52 +00009130
9131 // If the input is a shl/ashr pair of a same constant, then this is a sign
9132 // extension from a smaller value. If we could trust arbitrary bitwidth
9133 // integers, we could turn this into a truncate to the smaller bit and then
9134 // use a sext for the whole extension. Since we don't, look deeper and check
9135 // for a truncate. If the source and dest are the same type, eliminate the
9136 // trunc and extend and just do shifts. For example, turn:
9137 // %a = trunc i32 %i to i8
9138 // %b = shl i8 %a, 6
9139 // %c = ashr i8 %b, 6
9140 // %d = sext i8 %c to i32
9141 // into:
9142 // %a = shl i32 %i, 30
9143 // %d = ashr i32 %a, 30
9144 Value *A = 0;
9145 ConstantInt *BA = 0, *CA = 0;
9146 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00009147 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00009148 BA == CA && isa<TruncInst>(A)) {
9149 Value *I = cast<TruncInst>(A)->getOperand(0);
9150 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009151 unsigned MidSize = Src->getType()->getScalarSizeInBits();
9152 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00009153 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00009154 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009155 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00009156 return BinaryOperator::CreateAShr(I, ShAmtV);
9157 }
9158 }
9159
Chris Lattnerba417832007-04-11 06:12:58 +00009160 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009161}
9162
Chris Lattnerb7530652008-01-27 05:29:54 +00009163/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9164/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00009165static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009166 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00009167 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00009168 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00009169 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9170 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00009171 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00009172 return 0;
9173}
9174
9175/// LookThroughFPExtensions - If this is an fp extension instruction, look
9176/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00009177static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00009178 if (Instruction *I = dyn_cast<Instruction>(V))
9179 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00009180 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009181
9182 // If this value is a constant, return the constant in the smallest FP type
9183 // that can accurately represent it. This allows us to turn
9184 // (float)((double)X+2.0) into x+2.0f.
9185 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009186 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009187 return V; // No constant folding of this.
9188 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00009189 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009190 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00009191 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009192 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00009193 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009194 return V;
9195 // Don't try to shrink to various long double types.
9196 }
9197
9198 return V;
9199}
9200
9201Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9202 if (Instruction *I = commonCastTransforms(CI))
9203 return I;
9204
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009205 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00009206 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009207 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009208 // many builtins (sqrt, etc).
9209 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9210 if (OpI && OpI->hasOneUse()) {
9211 switch (OpI->getOpcode()) {
9212 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009213 case Instruction::FAdd:
9214 case Instruction::FSub:
9215 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009216 case Instruction::FDiv:
9217 case Instruction::FRem:
9218 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00009219 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9220 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009221 if (LHSTrunc->getType() != SrcTy &&
9222 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009223 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009224 // If the source types were both smaller than the destination type of
9225 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009226 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9227 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009228 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9229 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009230 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009231 }
9232 }
9233 break;
9234 }
9235 }
9236 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009237}
9238
9239Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9240 return commonCastTransforms(CI);
9241}
9242
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009243Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009244 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9245 if (OpI == 0)
9246 return commonCastTransforms(FI);
9247
9248 // fptoui(uitofp(X)) --> X
9249 // fptoui(sitofp(X)) --> X
9250 // This is safe if the intermediate type has enough bits in its mantissa to
9251 // accurately represent all values of X. For example, do not do this with
9252 // i64->float->i64. This is also safe for sitofp case, because any negative
9253 // 'X' value would cause an undefined result for the fptoui.
9254 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9255 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009256 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009257 OpI->getType()->getFPMantissaWidth())
9258 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009259
9260 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009261}
9262
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009263Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009264 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9265 if (OpI == 0)
9266 return commonCastTransforms(FI);
9267
9268 // fptosi(sitofp(X)) --> X
9269 // fptosi(uitofp(X)) --> X
9270 // This is safe if the intermediate type has enough bits in its mantissa to
9271 // accurately represent all values of X. For example, do not do this with
9272 // i64->float->i64. This is also safe for sitofp case, because any negative
9273 // 'X' value would cause an undefined result for the fptoui.
9274 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9275 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009276 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009277 OpI->getType()->getFPMantissaWidth())
9278 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009279
9280 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009281}
9282
9283Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9284 return commonCastTransforms(CI);
9285}
9286
9287Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9288 return commonCastTransforms(CI);
9289}
9290
Chris Lattnera0e69692009-03-24 18:35:40 +00009291Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9292 // If the destination integer type is smaller than the intptr_t type for
9293 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9294 // trunc to be exposed to other transforms. Don't do this for extending
9295 // ptrtoint's, because we don't know if the target sign or zero extends its
9296 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009297 if (TD &&
9298 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009299 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9300 TD->getIntPtrType(CI.getContext()),
9301 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009302 return new TruncInst(P, CI.getType());
9303 }
9304
Chris Lattnerd3e28342007-04-27 17:44:50 +00009305 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009306}
9307
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009308Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009309 // If the source integer type is larger than the intptr_t type for
9310 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9311 // allows the trunc to be exposed to other transforms. Don't do this for
9312 // extending inttoptr's, because we don't know if the target sign or zero
9313 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009314 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009315 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009316 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9317 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009318 return new IntToPtrInst(P, CI.getType());
9319 }
9320
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009321 if (Instruction *I = commonCastTransforms(CI))
9322 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009323
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009324 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009325}
9326
Chris Lattnerd3e28342007-04-27 17:44:50 +00009327Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009328 // If the operands are integer typed then apply the integer transforms,
9329 // otherwise just apply the common ones.
9330 Value *Src = CI.getOperand(0);
9331 const Type *SrcTy = Src->getType();
9332 const Type *DestTy = CI.getType();
9333
Eli Friedman7e25d452009-07-13 20:53:00 +00009334 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009335 if (Instruction *I = commonPointerCastTransforms(CI))
9336 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009337 } else {
9338 if (Instruction *Result = commonCastTransforms(CI))
9339 return Result;
9340 }
9341
9342
9343 // Get rid of casts from one type to the same type. These are useless and can
9344 // be replaced by the operand.
9345 if (DestTy == Src->getType())
9346 return ReplaceInstUsesWith(CI, Src);
9347
Reid Spencer3da59db2006-11-27 01:05:10 +00009348 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009349 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9350 const Type *DstElTy = DstPTy->getElementType();
9351 const Type *SrcElTy = SrcPTy->getElementType();
9352
Nate Begeman83ad90a2008-03-31 00:22:16 +00009353 // If the address spaces don't match, don't eliminate the bitcast, which is
9354 // required for changing types.
9355 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9356 return 0;
9357
Victor Hernandez83d63912009-09-18 22:35:49 +00009358 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009359 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009360 // There is no need to modify malloc calls because it is their bitcast that
9361 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009362 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009363 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9364 return V;
9365
Chris Lattnerd717c182007-05-05 22:32:24 +00009366 // If the source and destination are pointers, and this cast is equivalent
9367 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009368 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009369 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009370 unsigned NumZeros = 0;
9371 while (SrcElTy != DstElTy &&
9372 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9373 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9374 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9375 ++NumZeros;
9376 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009377
Chris Lattnerd3e28342007-04-27 17:44:50 +00009378 // If we found a path from the src to dest, create the getelementptr now.
9379 if (SrcElTy == DstElTy) {
9380 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009381 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9382 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009383 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009384 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009385
Eli Friedman2451a642009-07-18 23:06:53 +00009386 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9387 if (DestVTy->getNumElements() == 1) {
9388 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009389 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009390 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009391 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009392 }
9393 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9394 }
9395 }
9396
9397 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9398 if (SrcVTy->getNumElements() == 1) {
9399 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009400 Value *Elem =
9401 Builder->CreateExtractElement(Src,
9402 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009403 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9404 }
9405 }
9406 }
9407
Reid Spencer3da59db2006-11-27 01:05:10 +00009408 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9409 if (SVI->hasOneUse()) {
9410 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9411 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009412 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009413 cast<VectorType>(DestTy)->getNumElements() ==
9414 SVI->getType()->getNumElements() &&
9415 SVI->getType()->getNumElements() ==
9416 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009417 CastInst *Tmp;
9418 // If either of the operands is a cast from CI.getType(), then
9419 // evaluating the shuffle in the casted destination's type will allow
9420 // us to eliminate at least one cast.
9421 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9422 Tmp->getOperand(0)->getType() == DestTy) ||
9423 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9424 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009425 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9426 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009427 // Return a new shuffle vector. Use the same element ID's, as we
9428 // know the vector types match #elts.
9429 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009430 }
9431 }
9432 }
9433 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009434 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009435}
9436
Chris Lattnere576b912004-04-09 23:46:01 +00009437/// GetSelectFoldableOperands - We want to turn code that looks like this:
9438/// %C = or %A, %B
9439/// %D = select %cond, %C, %A
9440/// into:
9441/// %C = select %cond, %B, 0
9442/// %D = or %A, %C
9443///
9444/// Assuming that the specified instruction is an operand to the select, return
9445/// a bitmask indicating which operands of this instruction are foldable if they
9446/// equal the other incoming value of the select.
9447///
9448static unsigned GetSelectFoldableOperands(Instruction *I) {
9449 switch (I->getOpcode()) {
9450 case Instruction::Add:
9451 case Instruction::Mul:
9452 case Instruction::And:
9453 case Instruction::Or:
9454 case Instruction::Xor:
9455 return 3; // Can fold through either operand.
9456 case Instruction::Sub: // Can only fold on the amount subtracted.
9457 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009458 case Instruction::LShr:
9459 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009460 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009461 default:
9462 return 0; // Cannot fold
9463 }
9464}
9465
9466/// GetSelectFoldableConstant - For the same transformation as the previous
9467/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009468static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009469 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009470 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009471 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009472 case Instruction::Add:
9473 case Instruction::Sub:
9474 case Instruction::Or:
9475 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009476 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009477 case Instruction::LShr:
9478 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009479 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009480 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009481 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009482 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009483 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009484 }
9485}
9486
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009487/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9488/// have the same opcode and only one use each. Try to simplify this.
9489Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9490 Instruction *FI) {
9491 if (TI->getNumOperands() == 1) {
9492 // If this is a non-volatile load or a cast from the same type,
9493 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009494 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009495 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9496 return 0;
9497 } else {
9498 return 0; // unknown unary op.
9499 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009500
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009501 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009502 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009503 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009504 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009505 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009506 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009507 }
9508
Reid Spencer832254e2007-02-02 02:16:23 +00009509 // Only handle binary operators here.
9510 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009511 return 0;
9512
9513 // Figure out if the operations have any operands in common.
9514 Value *MatchOp, *OtherOpT, *OtherOpF;
9515 bool MatchIsOpZero;
9516 if (TI->getOperand(0) == FI->getOperand(0)) {
9517 MatchOp = TI->getOperand(0);
9518 OtherOpT = TI->getOperand(1);
9519 OtherOpF = FI->getOperand(1);
9520 MatchIsOpZero = true;
9521 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9522 MatchOp = TI->getOperand(1);
9523 OtherOpT = TI->getOperand(0);
9524 OtherOpF = FI->getOperand(0);
9525 MatchIsOpZero = false;
9526 } else if (!TI->isCommutative()) {
9527 return 0;
9528 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9529 MatchOp = TI->getOperand(0);
9530 OtherOpT = TI->getOperand(1);
9531 OtherOpF = FI->getOperand(0);
9532 MatchIsOpZero = true;
9533 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9534 MatchOp = TI->getOperand(1);
9535 OtherOpT = TI->getOperand(0);
9536 OtherOpF = FI->getOperand(1);
9537 MatchIsOpZero = true;
9538 } else {
9539 return 0;
9540 }
9541
9542 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009543 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9544 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009545 InsertNewInstBefore(NewSI, SI);
9546
9547 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9548 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009549 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009550 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009551 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009552 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009553 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009554 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009555}
9556
Evan Chengde621922009-03-31 20:42:45 +00009557static bool isSelect01(Constant *C1, Constant *C2) {
9558 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9559 if (!C1I)
9560 return false;
9561 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9562 if (!C2I)
9563 return false;
9564 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9565}
9566
9567/// FoldSelectIntoOp - Try fold the select into one of the operands to
9568/// facilitate further optimization.
9569Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9570 Value *FalseVal) {
9571 // See the comment above GetSelectFoldableOperands for a description of the
9572 // transformation we are doing here.
9573 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9574 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9575 !isa<Constant>(FalseVal)) {
9576 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9577 unsigned OpToFold = 0;
9578 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9579 OpToFold = 1;
9580 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9581 OpToFold = 2;
9582 }
9583
9584 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009585 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009586 Value *OOp = TVI->getOperand(2-OpToFold);
9587 // Avoid creating select between 2 constants unless it's selecting
9588 // between 0 and 1.
9589 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9590 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9591 InsertNewInstBefore(NewSel, SI);
9592 NewSel->takeName(TVI);
9593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9594 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009595 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009596 }
9597 }
9598 }
9599 }
9600 }
9601
9602 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9603 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9604 !isa<Constant>(TrueVal)) {
9605 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9606 unsigned OpToFold = 0;
9607 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9608 OpToFold = 1;
9609 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9610 OpToFold = 2;
9611 }
9612
9613 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009614 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009615 Value *OOp = FVI->getOperand(2-OpToFold);
9616 // Avoid creating select between 2 constants unless it's selecting
9617 // between 0 and 1.
9618 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9619 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9620 InsertNewInstBefore(NewSel, SI);
9621 NewSel->takeName(FVI);
9622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9623 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009624 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009625 }
9626 }
9627 }
9628 }
9629 }
9630
9631 return 0;
9632}
9633
Dan Gohman81b28ce2008-09-16 18:46:06 +00009634/// visitSelectInstWithICmp - Visit a SelectInst that has an
9635/// ICmpInst as its first operand.
9636///
9637Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9638 ICmpInst *ICI) {
9639 bool Changed = false;
9640 ICmpInst::Predicate Pred = ICI->getPredicate();
9641 Value *CmpLHS = ICI->getOperand(0);
9642 Value *CmpRHS = ICI->getOperand(1);
9643 Value *TrueVal = SI.getTrueValue();
9644 Value *FalseVal = SI.getFalseValue();
9645
9646 // Check cases where the comparison is with a constant that
9647 // can be adjusted to fit the min/max idiom. We may edit ICI in
9648 // place here, so make sure the select is the only user.
9649 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009650 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009651 switch (Pred) {
9652 default: break;
9653 case ICmpInst::ICMP_ULT:
9654 case ICmpInst::ICMP_SLT: {
9655 // X < MIN ? T : F --> F
9656 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9657 return ReplaceInstUsesWith(SI, FalseVal);
9658 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009659 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009660 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9661 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9662 Pred = ICmpInst::getSwappedPredicate(Pred);
9663 CmpRHS = AdjustedRHS;
9664 std::swap(FalseVal, TrueVal);
9665 ICI->setPredicate(Pred);
9666 ICI->setOperand(1, CmpRHS);
9667 SI.setOperand(1, TrueVal);
9668 SI.setOperand(2, FalseVal);
9669 Changed = true;
9670 }
9671 break;
9672 }
9673 case ICmpInst::ICMP_UGT:
9674 case ICmpInst::ICMP_SGT: {
9675 // X > MAX ? T : F --> F
9676 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9677 return ReplaceInstUsesWith(SI, FalseVal);
9678 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009679 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009680 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9681 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9682 Pred = ICmpInst::getSwappedPredicate(Pred);
9683 CmpRHS = AdjustedRHS;
9684 std::swap(FalseVal, TrueVal);
9685 ICI->setPredicate(Pred);
9686 ICI->setOperand(1, CmpRHS);
9687 SI.setOperand(1, TrueVal);
9688 SI.setOperand(2, FalseVal);
9689 Changed = true;
9690 }
9691 break;
9692 }
9693 }
9694
Dan Gohman1975d032008-10-30 20:40:10 +00009695 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9696 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009697 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009698 if (match(TrueVal, m_ConstantInt<-1>()) &&
9699 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009700 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009701 else if (match(TrueVal, m_ConstantInt<0>()) &&
9702 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009703 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9704
Dan Gohman1975d032008-10-30 20:40:10 +00009705 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9706 // If we are just checking for a icmp eq of a single bit and zext'ing it
9707 // to an integer, then shift the bit to the appropriate place and then
9708 // cast to integer to avoid the comparison.
9709 const APInt &Op1CV = CI->getValue();
9710
9711 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9712 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9713 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009714 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009715 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009716 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009717 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009718 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009719 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009720 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009721 if (In->getType() != SI.getType())
9722 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009723 true/*SExt*/, "tmp", ICI);
9724
9725 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009726 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009727 In->getName()+".not"), *ICI);
9728
9729 return ReplaceInstUsesWith(SI, In);
9730 }
9731 }
9732 }
9733
Dan Gohman81b28ce2008-09-16 18:46:06 +00009734 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9735 // Transform (X == Y) ? X : Y -> Y
9736 if (Pred == ICmpInst::ICMP_EQ)
9737 return ReplaceInstUsesWith(SI, FalseVal);
9738 // Transform (X != Y) ? X : Y -> X
9739 if (Pred == ICmpInst::ICMP_NE)
9740 return ReplaceInstUsesWith(SI, TrueVal);
9741 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9742
9743 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9744 // Transform (X == Y) ? Y : X -> X
9745 if (Pred == ICmpInst::ICMP_EQ)
9746 return ReplaceInstUsesWith(SI, FalseVal);
9747 // Transform (X != Y) ? Y : X -> Y
9748 if (Pred == ICmpInst::ICMP_NE)
9749 return ReplaceInstUsesWith(SI, TrueVal);
9750 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9751 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009752 return Changed ? &SI : 0;
9753}
9754
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009755
Chris Lattner7f239582009-10-22 00:17:26 +00009756/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9757/// PHI node (but the two may be in different blocks). See if the true/false
9758/// values (V) are live in all of the predecessor blocks of the PHI. For
9759/// example, cases like this cannot be mapped:
9760///
9761/// X = phi [ C1, BB1], [C2, BB2]
9762/// Y = add
9763/// Z = select X, Y, 0
9764///
9765/// because Y is not live in BB1/BB2.
9766///
9767static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9768 const SelectInst &SI) {
9769 // If the value is a non-instruction value like a constant or argument, it
9770 // can always be mapped.
9771 const Instruction *I = dyn_cast<Instruction>(V);
9772 if (I == 0) return true;
9773
9774 // If V is a PHI node defined in the same block as the condition PHI, we can
9775 // map the arguments.
9776 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9777
9778 if (const PHINode *VP = dyn_cast<PHINode>(I))
9779 if (VP->getParent() == CondPHI->getParent())
9780 return true;
9781
9782 // Otherwise, if the PHI and select are defined in the same block and if V is
9783 // defined in a different block, then we can transform it.
9784 if (SI.getParent() == CondPHI->getParent() &&
9785 I->getParent() != CondPHI->getParent())
9786 return true;
9787
9788 // Otherwise we have a 'hard' case and we can't tell without doing more
9789 // detailed dominator based analysis, punt.
9790 return false;
9791}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009792
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009793/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9794/// SPF2(SPF1(A, B), C)
9795Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9796 SelectPatternFlavor SPF1,
9797 Value *A, Value *B,
9798 Instruction &Outer,
9799 SelectPatternFlavor SPF2, Value *C) {
9800 if (C == A || C == B) {
9801 // MAX(MAX(A, B), B) -> MAX(A, B)
9802 // MIN(MIN(a, b), a) -> MIN(a, b)
9803 if (SPF1 == SPF2)
9804 return ReplaceInstUsesWith(Outer, Inner);
9805
9806 // MAX(MIN(a, b), a) -> a
9807 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009808 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9809 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9810 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9811 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009812 return ReplaceInstUsesWith(Outer, C);
9813 }
9814
9815 // TODO: MIN(MIN(A, 23), 97)
9816 return 0;
9817}
9818
9819
9820
9821
Chris Lattner3d69f462004-03-12 05:52:32 +00009822Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009823 Value *CondVal = SI.getCondition();
9824 Value *TrueVal = SI.getTrueValue();
9825 Value *FalseVal = SI.getFalseValue();
9826
9827 // select true, X, Y -> X
9828 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009829 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009830 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009831
9832 // select C, X, X -> X
9833 if (TrueVal == FalseVal)
9834 return ReplaceInstUsesWith(SI, TrueVal);
9835
Chris Lattnere87597f2004-10-16 18:11:37 +00009836 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9837 return ReplaceInstUsesWith(SI, FalseVal);
9838 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9839 return ReplaceInstUsesWith(SI, TrueVal);
9840 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9841 if (isa<Constant>(TrueVal))
9842 return ReplaceInstUsesWith(SI, TrueVal);
9843 else
9844 return ReplaceInstUsesWith(SI, FalseVal);
9845 }
9846
Owen Anderson1d0be152009-08-13 21:58:54 +00009847 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009848 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009849 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009850 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009851 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009852 } else {
9853 // Change: A = select B, false, C --> A = and !B, C
9854 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009855 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009856 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009857 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009858 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009859 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009860 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009861 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009862 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009863 } else {
9864 // Change: A = select B, C, true --> A = or !B, C
9865 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009866 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009867 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009868 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009869 }
9870 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009871
9872 // select a, b, a -> a&b
9873 // select a, a, b -> a|b
9874 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009875 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009876 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009877 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009878 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009879
Chris Lattner2eefe512004-04-09 19:05:30 +00009880 // Selecting between two integer constants?
9881 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9882 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009883 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009884 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009885 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009886 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009887 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009888 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009889 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009890 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009891 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009892 }
Chris Lattner457dd822004-06-09 07:59:58 +00009893
Reid Spencere4d87aa2006-12-23 06:05:41 +00009894 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009895 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009896 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009897 // non-constant value, eliminate this whole mess. This corresponds to
9898 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009899 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009900 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009901 cast<Constant>(IC->getOperand(1))->isNullValue())
9902 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9903 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009904 isa<ConstantInt>(ICA->getOperand(1)) &&
9905 (ICA->getOperand(1) == TrueValC ||
9906 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009907 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9908 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009909 // know whether we have a icmp_ne or icmp_eq and whether the
9910 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009911 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009912 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009913 Value *V = ICA;
9914 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009915 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009916 Instruction::Xor, V, ICA->getOperand(1)), SI);
9917 return ReplaceInstUsesWith(SI, V);
9918 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009919 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009920 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009921
9922 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009923 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9924 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009925 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009926 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9927 // This is not safe in general for floating point:
9928 // consider X== -0, Y== +0.
9929 // It becomes safe if either operand is a nonzero constant.
9930 ConstantFP *CFPt, *CFPf;
9931 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9932 !CFPt->getValueAPF().isZero()) ||
9933 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9934 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009935 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009936 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009937 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009938 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009939 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009940 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009941
Reid Spencere4d87aa2006-12-23 06:05:41 +00009942 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009943 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009944 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9945 // This is not safe in general for floating point:
9946 // consider X== -0, Y== +0.
9947 // It becomes safe if either operand is a nonzero constant.
9948 ConstantFP *CFPt, *CFPf;
9949 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9950 !CFPt->getValueAPF().isZero()) ||
9951 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9952 !CFPf->getValueAPF().isZero()))
9953 return ReplaceInstUsesWith(SI, FalseVal);
9954 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009955 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009956 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9957 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009958 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009959 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009960 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009961 }
9962
9963 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009964 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9965 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9966 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009967
Chris Lattner87875da2005-01-13 22:52:24 +00009968 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9969 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9970 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009971 Instruction *AddOp = 0, *SubOp = 0;
9972
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009973 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9974 if (TI->getOpcode() == FI->getOpcode())
9975 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9976 return IV;
9977
9978 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9979 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009980 if ((TI->getOpcode() == Instruction::Sub &&
9981 FI->getOpcode() == Instruction::Add) ||
9982 (TI->getOpcode() == Instruction::FSub &&
9983 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009984 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009985 } else if ((FI->getOpcode() == Instruction::Sub &&
9986 TI->getOpcode() == Instruction::Add) ||
9987 (FI->getOpcode() == Instruction::FSub &&
9988 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009989 AddOp = TI; SubOp = FI;
9990 }
9991
9992 if (AddOp) {
9993 Value *OtherAddOp = 0;
9994 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9995 OtherAddOp = AddOp->getOperand(1);
9996 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9997 OtherAddOp = AddOp->getOperand(0);
9998 }
9999
10000 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +000010001 // So at this point we know we have (Y -> OtherAddOp):
10002 // select C, (add X, Y), (sub X, Z)
10003 Value *NegVal; // Compute -Z
10004 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000010005 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +000010006 } else {
10007 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +000010008 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +000010009 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +000010010 }
Chris Lattner97f37a42006-02-24 18:05:58 +000010011
10012 Value *NewTrueOp = OtherAddOp;
10013 Value *NewFalseOp = NegVal;
10014 if (AddOp != TI)
10015 std::swap(NewTrueOp, NewFalseOp);
10016 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010017 SelectInst::Create(CondVal, NewTrueOp,
10018 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +000010019
10020 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010021 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +000010022 }
10023 }
10024 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010025
Chris Lattnere576b912004-04-09 23:46:01 +000010026 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +000010027 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010028 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +000010029 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010030
10031 // MAX(MAX(a, b), a) -> MAX(a, b)
10032 // MIN(MIN(a, b), a) -> MIN(a, b)
10033 // MAX(MIN(a, b), a) -> a
10034 // MIN(MAX(a, b), a) -> a
10035 Value *LHS, *RHS, *LHS2, *RHS2;
10036 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10037 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10038 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
10039 SI, SPF, RHS))
10040 return R;
10041 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10042 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10043 SI, SPF, LHS))
10044 return R;
10045 }
10046
10047 // TODO.
10048 // ABS(-X) -> ABS(X)
10049 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +000010050 }
Chris Lattnera1df33c2005-04-24 07:30:14 +000010051
Chris Lattner7f239582009-10-22 00:17:26 +000010052 // See if we can fold the select into a phi node if the condition is a select.
10053 if (isa<PHINode>(SI.getCondition()))
10054 // The true/false values have to be live in the PHI predecessor's blocks.
10055 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10056 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10057 if (Instruction *NV = FoldOpIntoPhi(SI))
10058 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +000010059
Chris Lattnera1df33c2005-04-24 07:30:14 +000010060 if (BinaryOperator::isNot(CondVal)) {
10061 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10062 SI.setOperand(1, FalseVal);
10063 SI.setOperand(2, TrueVal);
10064 return &SI;
10065 }
10066
Chris Lattner3d69f462004-03-12 05:52:32 +000010067 return 0;
10068}
10069
Dan Gohmaneee962e2008-04-10 18:43:06 +000010070/// EnforceKnownAlignment - If the specified pointer points to an object that
10071/// we control, modify the object's alignment to PrefAlign. This isn't
10072/// often possible though. If alignment is important, a more reliable approach
10073/// is to simply align all global variables and allocation instructions to
10074/// their preferred alignment from the beginning.
10075///
10076static unsigned EnforceKnownAlignment(Value *V,
10077 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +000010078
Dan Gohmaneee962e2008-04-10 18:43:06 +000010079 User *U = dyn_cast<User>(V);
10080 if (!U) return Align;
10081
Dan Gohmanca178902009-07-17 20:47:02 +000010082 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010083 default: break;
10084 case Instruction::BitCast:
10085 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10086 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +000010087 // If all indexes are zero, it is just the alignment of the base pointer.
10088 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +000010089 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +000010090 if (!isa<Constant>(*i) ||
10091 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +000010092 AllZeroOperands = false;
10093 break;
10094 }
Chris Lattnerf2369f22007-08-09 19:05:49 +000010095
10096 if (AllZeroOperands) {
10097 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010098 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +000010099 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010100 break;
Chris Lattner95a959d2006-03-06 20:18:44 +000010101 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010102 }
10103
10104 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10105 // If there is a large requested alignment and we can, bump up the alignment
10106 // of the global.
10107 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +000010108 if (GV->getAlignment() >= PrefAlign)
10109 Align = GV->getAlignment();
10110 else {
10111 GV->setAlignment(PrefAlign);
10112 Align = PrefAlign;
10113 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010114 }
Chris Lattner42ebefa2009-09-27 21:42:46 +000010115 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10116 // If there is a requested alignment and if this is an alloca, round up.
10117 if (AI->getAlignment() >= PrefAlign)
10118 Align = AI->getAlignment();
10119 else {
10120 AI->setAlignment(PrefAlign);
10121 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +000010122 }
10123 }
10124
10125 return Align;
10126}
10127
10128/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10129/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
10130/// and it is more than the alignment of the ultimate object, see if we can
10131/// increase the alignment of the ultimate object, making this check succeed.
10132unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10133 unsigned PrefAlign) {
10134 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10135 sizeof(PrefAlign) * CHAR_BIT;
10136 APInt Mask = APInt::getAllOnesValue(BitWidth);
10137 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10138 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10139 unsigned TrailZ = KnownZero.countTrailingOnes();
10140 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10141
10142 if (PrefAlign > Align)
10143 Align = EnforceKnownAlignment(V, Align, PrefAlign);
10144
10145 // We don't need to make any adjustment.
10146 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +000010147}
10148
Chris Lattnerf497b022008-01-13 23:50:23 +000010149Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010150 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +000010151 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +000010152 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010153 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +000010154
10155 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010156 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010157 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +000010158 return MI;
10159 }
10160
10161 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10162 // load/store.
10163 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10164 if (MemOpLength == 0) return 0;
10165
Chris Lattner37ac6082008-01-14 00:28:35 +000010166 // Source and destination pointer types are always "i8*" for intrinsic. See
10167 // if the size is something we can handle with a single primitive load/store.
10168 // A single load+store correctly handles overlapping memory in the memmove
10169 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +000010170 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010171 if (Size == 0) return MI; // Delete this mem transfer.
10172
10173 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +000010174 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +000010175
Chris Lattner37ac6082008-01-14 00:28:35 +000010176 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +000010177 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +000010178 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +000010179
10180 // Memcpy forces the use of i8* for the source and destination. That means
10181 // that if you're using memcpy to move one double around, you'll get a cast
10182 // from double* to i8*. We'd much rather use a double load+store rather than
10183 // an i64 load+store, here because this improves the odds that the source or
10184 // dest address will be promotable. See if we can find a better type than the
10185 // integer datatype.
10186 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10187 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010188 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010189 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10190 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +000010191 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010192 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10193 if (STy->getNumElements() == 1)
10194 SrcETy = STy->getElementType(0);
10195 else
10196 break;
10197 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10198 if (ATy->getNumElements() == 1)
10199 SrcETy = ATy->getElementType();
10200 else
10201 break;
10202 } else
10203 break;
10204 }
10205
Dan Gohman8f8e2692008-05-23 01:52:21 +000010206 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +000010207 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010208 }
10209 }
10210
10211
Chris Lattnerf497b022008-01-13 23:50:23 +000010212 // If the memcpy/memmove provides better alignment info than we can
10213 // infer, use it.
10214 SrcAlign = std::max(SrcAlign, CopyAlign);
10215 DstAlign = std::max(DstAlign, CopyAlign);
10216
Chris Lattner08142f22009-08-30 19:47:22 +000010217 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10218 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010219 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10220 InsertNewInstBefore(L, *MI);
10221 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10222
10223 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010224 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010225 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010226}
Chris Lattner3d69f462004-03-12 05:52:32 +000010227
Chris Lattner69ea9d22008-04-30 06:39:11 +000010228Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10229 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010230 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010231 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010232 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010233 return MI;
10234 }
10235
10236 // Extract the length and alignment and fill if they are constant.
10237 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10238 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +000010239 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010240 return 0;
10241 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010242 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010243
10244 // If the length is zero, this is a no-op
10245 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10246
10247 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10248 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010249 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010250
10251 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010252 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010253
10254 // Alignment 0 is identity for alignment 1 for memset, but not store.
10255 if (Alignment == 0) Alignment = 1;
10256
10257 // Extract the fill value and store.
10258 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010259 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010260 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010261
10262 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010263 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010264 return MI;
10265 }
10266
10267 return 0;
10268}
10269
10270
Chris Lattner8b0ea312006-01-13 20:11:04 +000010271/// visitCallInst - CallInst simplification. This mostly only handles folding
10272/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10273/// the heavy lifting.
10274///
Chris Lattner9fe38862003-06-19 17:00:31 +000010275Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010276 if (isFreeCall(&CI))
10277 return visitFree(CI);
10278
Chris Lattneraab6ec42009-05-13 17:39:14 +000010279 // If the caller function is nounwind, mark the call as nounwind, even if the
10280 // callee isn't.
10281 if (CI.getParent()->getParent()->doesNotThrow() &&
10282 !CI.doesNotThrow()) {
10283 CI.setDoesNotThrow();
10284 return &CI;
10285 }
10286
Chris Lattner8b0ea312006-01-13 20:11:04 +000010287 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10288 if (!II) return visitCallSite(&CI);
10289
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010290 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10291 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010292 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010293 bool Changed = false;
10294
10295 // memmove/cpy/set of zero bytes is a noop.
10296 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10297 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10298
Chris Lattner35b9e482004-10-12 04:52:52 +000010299 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010300 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010301 // Replace the instruction with just byte operations. We would
10302 // transform other cases to loads/stores, but we don't know if
10303 // alignment is sufficient.
10304 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010305 }
10306
Chris Lattner35b9e482004-10-12 04:52:52 +000010307 // If we have a memmove and the source operation is a constant global,
10308 // then the source and dest pointers can't alias, so we can change this
10309 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010310 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010311 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10312 if (GVSrc->isConstant()) {
10313 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010314 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10315 const Type *Tys[1];
10316 Tys[0] = CI.getOperand(3)->getType();
10317 CI.setOperand(0,
10318 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010319 Changed = true;
10320 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010321 }
Chris Lattnera935db82008-05-28 05:30:41 +000010322
Eli Friedman0c826d92009-12-17 21:07:31 +000010323 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010324 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010325 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010326 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010327 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010328
Chris Lattner95a959d2006-03-06 20:18:44 +000010329 // If we can determine a pointer alignment that is bigger than currently
10330 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010331 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010332 if (Instruction *I = SimplifyMemTransfer(MI))
10333 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010334 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10335 if (Instruction *I = SimplifyMemSet(MSI))
10336 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010337 }
10338
Chris Lattner8b0ea312006-01-13 20:11:04 +000010339 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010340 }
10341
10342 switch (II->getIntrinsicID()) {
10343 default: break;
10344 case Intrinsic::bswap:
10345 // bswap(bswap(x)) -> x
10346 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10347 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10348 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010349
10350 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10351 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10352 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10353 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10354 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10355 TI->getType()->getPrimitiveSizeInBits();
10356 Value *CV = ConstantInt::get(Operand->getType(), C);
10357 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10358 return new TruncInst(V, TI->getType());
10359 }
10360 }
10361
Chris Lattner0521e3c2008-06-18 04:33:20 +000010362 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010363 case Intrinsic::powi:
10364 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10365 // powi(x, 0) -> 1.0
10366 if (Power->isZero())
10367 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10368 // powi(x, 1) -> x
10369 if (Power->isOne())
10370 return ReplaceInstUsesWith(CI, II->getOperand(1));
10371 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010372 if (Power->isAllOnesValue())
10373 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10374 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010375 }
10376 break;
10377
Chris Lattner2bbac752009-11-26 21:42:47 +000010378 case Intrinsic::uadd_with_overflow: {
10379 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10380 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10381 uint32_t BitWidth = IT->getBitWidth();
10382 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010383 APInt LHSKnownZero(BitWidth, 0);
10384 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010385 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10386 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10387 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10388
10389 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010390 APInt RHSKnownZero(BitWidth, 0);
10391 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010392 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10393 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10394 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10395 if (LHSKnownNegative && RHSKnownNegative) {
10396 // The sign bit is set in both cases: this MUST overflow.
10397 // Create a simple add instruction, and insert it into the struct.
10398 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10399 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010400 Constant *V[] = {
10401 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10402 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010403 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10404 return InsertValueInst::Create(Struct, Add, 0);
10405 }
10406
10407 if (LHSKnownPositive && RHSKnownPositive) {
10408 // The sign bit is clear in both cases: this CANNOT overflow.
10409 // Create a simple add instruction, and insert it into the struct.
10410 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10411 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010412 Constant *V[] = {
10413 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10414 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010415 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10416 return InsertValueInst::Create(Struct, Add, 0);
10417 }
10418 }
10419 }
10420 // FALL THROUGH uadd into sadd
10421 case Intrinsic::sadd_with_overflow:
10422 // Canonicalize constants into the RHS.
10423 if (isa<Constant>(II->getOperand(1)) &&
10424 !isa<Constant>(II->getOperand(2))) {
10425 Value *LHS = II->getOperand(1);
10426 II->setOperand(1, II->getOperand(2));
10427 II->setOperand(2, LHS);
10428 return II;
10429 }
10430
10431 // X + undef -> undef
10432 if (isa<UndefValue>(II->getOperand(2)))
10433 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10434
10435 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10436 // X + 0 -> {X, false}
10437 if (RHS->isZero()) {
10438 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010439 UndefValue::get(II->getOperand(0)->getType()),
10440 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010441 };
10442 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10443 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10444 }
10445 }
10446 break;
10447 case Intrinsic::usub_with_overflow:
10448 case Intrinsic::ssub_with_overflow:
10449 // undef - X -> undef
10450 // X - undef -> undef
10451 if (isa<UndefValue>(II->getOperand(1)) ||
10452 isa<UndefValue>(II->getOperand(2)))
10453 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10454
10455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10456 // X - 0 -> {X, false}
10457 if (RHS->isZero()) {
10458 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010459 UndefValue::get(II->getOperand(1)->getType()),
10460 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010461 };
10462 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10463 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10464 }
10465 }
10466 break;
10467 case Intrinsic::umul_with_overflow:
10468 case Intrinsic::smul_with_overflow:
10469 // Canonicalize constants into the RHS.
10470 if (isa<Constant>(II->getOperand(1)) &&
10471 !isa<Constant>(II->getOperand(2))) {
10472 Value *LHS = II->getOperand(1);
10473 II->setOperand(1, II->getOperand(2));
10474 II->setOperand(2, LHS);
10475 return II;
10476 }
10477
10478 // X * undef -> undef
10479 if (isa<UndefValue>(II->getOperand(2)))
10480 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10481
10482 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10483 // X*0 -> {0, false}
10484 if (RHSI->isZero())
10485 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10486
10487 // X * 1 -> {X, false}
10488 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010489 Constant *V[] = {
10490 UndefValue::get(II->getOperand(1)->getType()),
10491 ConstantInt::getFalse(*Context)
10492 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010493 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010494 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010495 }
10496 }
10497 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010498 case Intrinsic::ppc_altivec_lvx:
10499 case Intrinsic::ppc_altivec_lvxl:
10500 case Intrinsic::x86_sse_loadu_ps:
10501 case Intrinsic::x86_sse2_loadu_pd:
10502 case Intrinsic::x86_sse2_loadu_dq:
10503 // Turn PPC lvx -> load if the pointer is known aligned.
10504 // Turn X86 loadups -> load if the pointer is known aligned.
10505 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010506 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10507 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010508 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010509 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010510 break;
10511 case Intrinsic::ppc_altivec_stvx:
10512 case Intrinsic::ppc_altivec_stvxl:
10513 // Turn stvx -> store if the pointer is known aligned.
10514 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10515 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010516 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010517 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010518 return new StoreInst(II->getOperand(1), Ptr);
10519 }
10520 break;
10521 case Intrinsic::x86_sse_storeu_ps:
10522 case Intrinsic::x86_sse2_storeu_pd:
10523 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010524 // Turn X86 storeu -> store if the pointer is known aligned.
10525 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10526 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010527 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010528 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010529 return new StoreInst(II->getOperand(2), Ptr);
10530 }
10531 break;
10532
10533 case Intrinsic::x86_sse_cvttss2si: {
10534 // These intrinsics only demands the 0th element of its input vector. If
10535 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010536 unsigned VWidth =
10537 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10538 APInt DemandedElts(VWidth, 1);
10539 APInt UndefElts(VWidth, 0);
10540 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010541 UndefElts)) {
10542 II->setOperand(1, V);
10543 return II;
10544 }
10545 break;
10546 }
10547
10548 case Intrinsic::ppc_altivec_vperm:
10549 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10550 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10551 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010552
Chris Lattner0521e3c2008-06-18 04:33:20 +000010553 // Check that all of the elements are integer constants or undefs.
10554 bool AllEltsOk = true;
10555 for (unsigned i = 0; i != 16; ++i) {
10556 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10557 !isa<UndefValue>(Mask->getOperand(i))) {
10558 AllEltsOk = false;
10559 break;
10560 }
10561 }
10562
10563 if (AllEltsOk) {
10564 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010565 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10566 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010567 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010568
Chris Lattner0521e3c2008-06-18 04:33:20 +000010569 // Only extract each element once.
10570 Value *ExtractedElts[32];
10571 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10572
Chris Lattnere2ed0572006-04-06 19:19:17 +000010573 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010574 if (isa<UndefValue>(Mask->getOperand(i)))
10575 continue;
10576 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10577 Idx &= 31; // Match the hardware behavior.
10578
10579 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010580 ExtractedElts[Idx] =
10581 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10582 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10583 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010584 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010585
Chris Lattner0521e3c2008-06-18 04:33:20 +000010586 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010587 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10588 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10589 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010590 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010591 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010592 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010593 }
10594 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010595
Chris Lattner0521e3c2008-06-18 04:33:20 +000010596 case Intrinsic::stackrestore: {
10597 // If the save is right next to the restore, remove the restore. This can
10598 // happen when variable allocas are DCE'd.
10599 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10600 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10601 BasicBlock::iterator BI = SS;
10602 if (&*++BI == II)
10603 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010604 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010605 }
10606
10607 // Scan down this block to see if there is another stack restore in the
10608 // same block without an intervening call/alloca.
10609 BasicBlock::iterator BI = II;
10610 TerminatorInst *TI = II->getParent()->getTerminator();
10611 bool CannotRemove = false;
10612 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010613 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010614 CannotRemove = true;
10615 break;
10616 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010617 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10618 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10619 // If there is a stackrestore below this one, remove this one.
10620 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10621 return EraseInstFromFunction(CI);
10622 // Otherwise, ignore the intrinsic.
10623 } else {
10624 // If we found a non-intrinsic call, we can't remove the stack
10625 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010626 CannotRemove = true;
10627 break;
10628 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010629 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010630 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010631
10632 // If the stack restore is in a return/unwind block and if there are no
10633 // allocas or calls between the restore and the return, nuke the restore.
10634 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10635 return EraseInstFromFunction(CI);
10636 break;
10637 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010638 }
10639
Chris Lattner8b0ea312006-01-13 20:11:04 +000010640 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010641}
10642
10643// InvokeInst simplification
10644//
10645Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010646 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010647}
10648
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010649/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10650/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010651static bool isSafeToEliminateVarargsCast(const CallSite CS,
10652 const CastInst * const CI,
10653 const TargetData * const TD,
10654 const int ix) {
10655 if (!CI->isLosslessCast())
10656 return false;
10657
10658 // The size of ByVal arguments is derived from the type, so we
10659 // can't change to a type with a different size. If the size were
10660 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010661 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010662 return true;
10663
10664 const Type* SrcTy =
10665 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10666 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10667 if (!SrcTy->isSized() || !DstTy->isSized())
10668 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010669 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010670 return false;
10671 return true;
10672}
10673
Chris Lattnera44d8a22003-10-07 22:32:43 +000010674// visitCallSite - Improvements for call and invoke instructions.
10675//
10676Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010677 bool Changed = false;
10678
10679 // If the callee is a constexpr cast of a function, attempt to move the cast
10680 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010681 if (transformConstExprCastCall(CS)) return 0;
10682
Chris Lattner6c266db2003-10-07 22:54:13 +000010683 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010684
Chris Lattner08b22ec2005-05-13 07:09:09 +000010685 if (Function *CalleeF = dyn_cast<Function>(Callee))
10686 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10687 Instruction *OldCall = CS.getInstruction();
10688 // If the call and callee calling conventions don't match, this call must
10689 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010690 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010691 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010692 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010693 // If OldCall dues not return void then replaceAllUsesWith undef.
10694 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010695 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010696 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010697 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10698 return EraseInstFromFunction(*OldCall);
10699 return 0;
10700 }
10701
Chris Lattner17be6352004-10-18 02:59:09 +000010702 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10703 // This instruction is not reachable, just remove it. We insert a store to
10704 // undef so that we know that this code is not reachable, despite the fact
10705 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010706 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010707 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010708 CS.getInstruction());
10709
Devang Patel228ebd02009-10-13 22:56:32 +000010710 // If CS dues not return void then replaceAllUsesWith undef.
10711 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010712 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010713 CS.getInstruction()->
10714 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010715
10716 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10717 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010718 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010719 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010720 }
Chris Lattner17be6352004-10-18 02:59:09 +000010721 return EraseInstFromFunction(*CS.getInstruction());
10722 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010723
Duncan Sandscdb6d922007-09-17 10:26:40 +000010724 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10725 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10726 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10727 return transformCallThroughTrampoline(CS);
10728
Chris Lattner6c266db2003-10-07 22:54:13 +000010729 const PointerType *PTy = cast<PointerType>(Callee->getType());
10730 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10731 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010732 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010733 // See if we can optimize any arguments passed through the varargs area of
10734 // the call.
10735 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010736 E = CS.arg_end(); I != E; ++I, ++ix) {
10737 CastInst *CI = dyn_cast<CastInst>(*I);
10738 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10739 *I = CI->getOperand(0);
10740 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010741 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010742 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010743 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010744
Duncan Sandsf0c33542007-12-19 21:13:37 +000010745 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010746 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010747 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010748 Changed = true;
10749 }
10750
Chris Lattner6c266db2003-10-07 22:54:13 +000010751 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010752}
10753
Chris Lattner9fe38862003-06-19 17:00:31 +000010754// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10755// attempt to move the cast to the arguments of the call/invoke.
10756//
10757bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10758 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10759 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010760 if (CE->getOpcode() != Instruction::BitCast ||
10761 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010762 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010763 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010764 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010765 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010766
10767 // Okay, this is a cast from a function to a different type. Unless doing so
10768 // would cause a type conversion of one of our arguments, change this call to
10769 // be a direct call with arguments casted to the appropriate types.
10770 //
10771 const FunctionType *FT = Callee->getFunctionType();
10772 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010773 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010774
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010775 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010776 return false; // TODO: Handle multiple return values.
10777
Chris Lattnerf78616b2004-01-14 06:06:08 +000010778 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010779 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010780 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010781 // Conversion is ok if changing from one pointer type to another or from
10782 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010783 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010784 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010785 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010786 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010787 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010788
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010789 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010790 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010791 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010792 return false; // Cannot transform this return value.
10793
Chris Lattner58d74912008-03-12 17:45:29 +000010794 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010795 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010796 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010797 return false; // Attribute not compatible with transformed value.
10798 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010799
Chris Lattnerf78616b2004-01-14 06:06:08 +000010800 // If the callsite is an invoke instruction, and the return value is used by
10801 // a PHI node in a successor, we cannot change the return type of the call
10802 // because there is no place to put the cast instruction (without breaking
10803 // the critical edge). Bail out in this case.
10804 if (!Caller->use_empty())
10805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10806 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10807 UI != E; ++UI)
10808 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10809 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010810 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010811 return false;
10812 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010813
10814 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10815 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010816
Chris Lattner9fe38862003-06-19 17:00:31 +000010817 CallSite::arg_iterator AI = CS.arg_begin();
10818 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10819 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010820 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010821
10822 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010823 return false; // Cannot transform this parameter value.
10824
Devang Patel19c87462008-09-26 22:53:05 +000010825 if (CallerPAL.getParamAttributes(i + 1)
10826 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010827 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010828
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010829 // Converting from one pointer type to another or between a pointer and an
10830 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010831 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010832 (TD && ((isa<PointerType>(ParamTy) ||
10833 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10834 (isa<PointerType>(ActTy) ||
10835 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010836 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010837 }
10838
10839 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010840 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010841 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010842
Chris Lattner58d74912008-03-12 17:45:29 +000010843 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10844 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010845 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010846 // won't be dropping them. Check that these extra arguments have attributes
10847 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010848 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10849 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010850 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010851 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010852 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010853 return false;
10854 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010855
Chris Lattner9fe38862003-06-19 17:00:31 +000010856 // Okay, we decided that this is a safe thing to do: go ahead and start
10857 // inserting cast instructions as necessary...
10858 std::vector<Value*> Args;
10859 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010860 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010861 attrVec.reserve(NumCommonArgs);
10862
10863 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010864 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010865
10866 // If the return value is not being used, the type may not be compatible
10867 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010868 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010869
10870 // Add the new return attributes.
10871 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010872 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010873
10874 AI = CS.arg_begin();
10875 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10876 const Type *ParamTy = FT->getParamType(i);
10877 if ((*AI)->getType() == ParamTy) {
10878 Args.push_back(*AI);
10879 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010880 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010881 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010882 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010883 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010884
10885 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010886 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010887 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010888 }
10889
10890 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010891 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010892 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010893 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010894
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010895 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010896 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010897 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010898 errs() << "WARNING: While resolving call to function '"
10899 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010900 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010901 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010902 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10903 const Type *PTy = getPromotedType((*AI)->getType());
10904 if (PTy != (*AI)->getType()) {
10905 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010906 Instruction::CastOps opcode =
10907 CastInst::getCastOpcode(*AI, false, PTy, false);
10908 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010909 } else {
10910 Args.push_back(*AI);
10911 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010912
Duncan Sandse1e520f2008-01-13 08:02:44 +000010913 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010914 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010915 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010916 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010917 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010918 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010919
Devang Patel19c87462008-09-26 22:53:05 +000010920 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10921 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10922
Devang Patel9674d152009-10-14 17:29:00 +000010923 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010924 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010925
Eric Christophera66297a2009-07-25 02:45:27 +000010926 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10927 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010928
Chris Lattner9fe38862003-06-19 17:00:31 +000010929 Instruction *NC;
10930 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010931 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010932 Args.begin(), Args.end(),
10933 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010934 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010935 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010936 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010937 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10938 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010939 CallInst *CI = cast<CallInst>(Caller);
10940 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010941 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010942 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010943 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010944 }
10945
Chris Lattner6934a042007-02-11 01:23:03 +000010946 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010947 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010948 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010949 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010950 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010951 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010952 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010953
10954 // If this is an invoke instruction, we should insert it after the first
10955 // non-phi, instruction in the normal successor block.
10956 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010957 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010958 InsertNewInstBefore(NC, *I);
10959 } else {
10960 // Otherwise, it's a call, just insert cast right after the call instr
10961 InsertNewInstBefore(NC, *Caller);
10962 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010963 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010964 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010965 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010966 }
10967 }
10968
Devang Patel1bf5ebc2009-10-13 21:41:20 +000010969
Chris Lattner931f8f32009-08-31 05:17:58 +000010970 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010971 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010972
10973 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010974 return true;
10975}
10976
Duncan Sandscdb6d922007-09-17 10:26:40 +000010977// transformCallThroughTrampoline - Turn a call to a function created by the
10978// init_trampoline intrinsic into a direct call to the underlying function.
10979//
10980Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10981 Value *Callee = CS.getCalledValue();
10982 const PointerType *PTy = cast<PointerType>(Callee->getType());
10983 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010984 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010985
10986 // If the call already has the 'nest' attribute somewhere then give up -
10987 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010988 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010989 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010990
10991 IntrinsicInst *Tramp =
10992 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10993
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010994 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010995 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10996 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10997
Devang Patel05988662008-09-25 21:00:45 +000010998 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010999 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011000 unsigned NestIdx = 1;
11001 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000011002 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011003
11004 // Look for a parameter marked with the 'nest' attribute.
11005 for (FunctionType::param_iterator I = NestFTy->param_begin(),
11006 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000011007 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011008 // Record the parameter type and any other attributes.
11009 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000011010 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011011 break;
11012 }
11013
11014 if (NestTy) {
11015 Instruction *Caller = CS.getInstruction();
11016 std::vector<Value*> NewArgs;
11017 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11018
Devang Patel05988662008-09-25 21:00:45 +000011019 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000011020 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011021
Duncan Sandscdb6d922007-09-17 10:26:40 +000011022 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011023 // mean appending it. Likewise for attributes.
11024
Devang Patel19c87462008-09-26 22:53:05 +000011025 // Add any result attributes.
11026 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000011027 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011028
Duncan Sandscdb6d922007-09-17 10:26:40 +000011029 {
11030 unsigned Idx = 1;
11031 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11032 do {
11033 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011034 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011035 Value *NestVal = Tramp->getOperand(3);
11036 if (NestVal->getType() != NestTy)
11037 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11038 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000011039 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011040 }
11041
11042 if (I == E)
11043 break;
11044
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011045 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011046 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000011047 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011048 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000011049 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011050
11051 ++Idx, ++I;
11052 } while (1);
11053 }
11054
Devang Patel19c87462008-09-26 22:53:05 +000011055 // Add any function attributes.
11056 if (Attributes Attr = Attrs.getFnAttributes())
11057 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11058
Duncan Sandscdb6d922007-09-17 10:26:40 +000011059 // The trampoline may have been bitcast to a bogus type (FTy).
11060 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011061 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011062
Duncan Sandscdb6d922007-09-17 10:26:40 +000011063 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011064 NewTypes.reserve(FTy->getNumParams()+1);
11065
Duncan Sandscdb6d922007-09-17 10:26:40 +000011066 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011067 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011068 {
11069 unsigned Idx = 1;
11070 FunctionType::param_iterator I = FTy->param_begin(),
11071 E = FTy->param_end();
11072
11073 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011074 if (Idx == NestIdx)
11075 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011076 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011077
11078 if (I == E)
11079 break;
11080
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011081 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011082 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011083
11084 ++Idx, ++I;
11085 } while (1);
11086 }
11087
11088 // Replace the trampoline call with a direct call. Let the generic
11089 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000011090 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000011091 FTy->isVarArg());
11092 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000011093 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000011094 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000011095 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000011096 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11097 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011098
11099 Instruction *NewCaller;
11100 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011101 NewCaller = InvokeInst::Create(NewCallee,
11102 II->getNormalDest(), II->getUnwindDest(),
11103 NewArgs.begin(), NewArgs.end(),
11104 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011105 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011106 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011107 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011108 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11109 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011110 if (cast<CallInst>(Caller)->isTailCall())
11111 cast<CallInst>(NewCaller)->setTailCall();
11112 cast<CallInst>(NewCaller)->
11113 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011114 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011115 }
Devang Patel9674d152009-10-14 17:29:00 +000011116 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000011117 Caller->replaceAllUsesWith(NewCaller);
11118 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000011119 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011120 return 0;
11121 }
11122 }
11123
11124 // Replace the trampoline call with a direct call. Since there is no 'nest'
11125 // parameter, there is no need to adjust the argument list. Let the generic
11126 // code sort out any function type mismatches.
11127 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000011128 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000011129 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011130 CS.setCalledFunction(NewCallee);
11131 return CS.getInstruction();
11132}
11133
Dan Gohman9ad29202009-09-16 16:50:24 +000011134/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11135/// 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 +000011136/// and a single binop.
11137Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11138 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011139 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000011140 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011141 Value *LHSVal = FirstInst->getOperand(0);
11142 Value *RHSVal = FirstInst->getOperand(1);
11143
11144 const Type *LHSType = LHSVal->getType();
11145 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000011146
Dan Gohman9ad29202009-09-16 16:50:24 +000011147 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011148 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000011149 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000011150 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000011151 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000011152 // types or GEP's with different index types.
11153 I->getOperand(0)->getType() != LHSType ||
11154 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000011155 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011156
11157 // If they are CmpInst instructions, check their predicates
11158 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11159 if (cast<CmpInst>(I)->getPredicate() !=
11160 cast<CmpInst>(FirstInst)->getPredicate())
11161 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011162
11163 // Keep track of which operand needs a phi node.
11164 if (I->getOperand(0) != LHSVal) LHSVal = 0;
11165 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011166 }
Dan Gohman9ad29202009-09-16 16:50:24 +000011167
11168 // If both LHS and RHS would need a PHI, don't do this transformation,
11169 // because it would increase the number of PHIs entering the block,
11170 // which leads to higher register pressure. This is especially
11171 // bad when the PHIs are in the header of a loop.
11172 if (!LHSVal && !RHSVal)
11173 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011174
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011175 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000011176
Chris Lattner7da52b22006-11-01 04:51:18 +000011177 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000011178 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000011179 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011180 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011181 NewLHS = PHINode::Create(LHSType,
11182 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011183 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11184 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011185 InsertNewInstBefore(NewLHS, PN);
11186 LHSVal = NewLHS;
11187 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011188
11189 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011190 NewRHS = PHINode::Create(RHSType,
11191 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011192 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11193 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011194 InsertNewInstBefore(NewRHS, PN);
11195 RHSVal = NewRHS;
11196 }
11197
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011198 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000011199 if (NewLHS || NewRHS) {
11200 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11201 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11202 if (NewLHS) {
11203 Value *NewInLHS = InInst->getOperand(0);
11204 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11205 }
11206 if (NewRHS) {
11207 Value *NewInRHS = InInst->getOperand(1);
11208 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11209 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011210 }
11211 }
11212
Chris Lattner7da52b22006-11-01 04:51:18 +000011213 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011214 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011215 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000011216 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000011217 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000011218}
11219
Chris Lattner05f18922008-12-01 02:34:36 +000011220Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11221 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11222
11223 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11224 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011225 // This is true if all GEP bases are allocas and if all indices into them are
11226 // constants.
11227 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011228
11229 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011230 // more than one phi, which leads to higher register pressure. This is
11231 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011232 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011233
Dan Gohman9ad29202009-09-16 16:50:24 +000011234 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011235 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11236 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11237 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11238 GEP->getNumOperands() != FirstInst->getNumOperands())
11239 return 0;
11240
Chris Lattner36d3e322009-02-21 00:46:50 +000011241 // Keep track of whether or not all GEPs are of alloca pointers.
11242 if (AllBasePointersAreAllocas &&
11243 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11244 !GEP->hasAllConstantIndices()))
11245 AllBasePointersAreAllocas = false;
11246
Chris Lattner05f18922008-12-01 02:34:36 +000011247 // Compare the operand lists.
11248 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11249 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11250 continue;
11251
11252 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11253 // if one of the PHIs has a constant for the index. The index may be
11254 // substantially cheaper to compute for the constants, so making it a
11255 // variable index could pessimize the path. This also handles the case
11256 // for struct indices, which must always be constant.
11257 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11258 isa<ConstantInt>(GEP->getOperand(op)))
11259 return 0;
11260
11261 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11262 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011263
11264 // If we already needed a PHI for an earlier operand, and another operand
11265 // also requires a PHI, we'd be introducing more PHIs than we're
11266 // eliminating, which increases register pressure on entry to the PHI's
11267 // block.
11268 if (NeededPhi)
11269 return 0;
11270
Chris Lattner05f18922008-12-01 02:34:36 +000011271 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011272 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011273 }
11274 }
11275
Chris Lattner36d3e322009-02-21 00:46:50 +000011276 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011277 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011278 // offset calculation, but all the predecessors will have to materialize the
11279 // stack address into a register anyway. We'd actually rather *clone* the
11280 // load up into the predecessors so that we have a load of a gep of an alloca,
11281 // which can usually all be folded into the load.
11282 if (AllBasePointersAreAllocas)
11283 return 0;
11284
Chris Lattner05f18922008-12-01 02:34:36 +000011285 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11286 // that is variable.
11287 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11288
11289 bool HasAnyPHIs = false;
11290 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11291 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11292 Value *FirstOp = FirstInst->getOperand(i);
11293 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11294 FirstOp->getName()+".pn");
11295 InsertNewInstBefore(NewPN, PN);
11296
11297 NewPN->reserveOperandSpace(e);
11298 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11299 OperandPhis[i] = NewPN;
11300 FixedOperands[i] = NewPN;
11301 HasAnyPHIs = true;
11302 }
11303
11304
11305 // Add all operands to the new PHIs.
11306 if (HasAnyPHIs) {
11307 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11308 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11309 BasicBlock *InBB = PN.getIncomingBlock(i);
11310
11311 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11312 if (PHINode *OpPhi = OperandPhis[op])
11313 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11314 }
11315 }
11316
11317 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011318 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11319 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11320 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011321 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11322 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011323}
11324
11325
Chris Lattner21550882009-02-23 05:56:17 +000011326/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11327/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011328/// obvious the value of the load is not changed from the point of the load to
11329/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011330///
11331/// Finally, it is safe, but not profitable, to sink a load targetting a
11332/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11333/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011334static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011335 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11336
11337 for (++BBI; BBI != E; ++BBI)
11338 if (BBI->mayWriteToMemory())
11339 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011340
11341 // Check for non-address taken alloca. If not address-taken already, it isn't
11342 // profitable to do this xform.
11343 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11344 bool isAddressTaken = false;
11345 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11346 UI != E; ++UI) {
11347 if (isa<LoadInst>(UI)) continue;
11348 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11349 // If storing TO the alloca, then the address isn't taken.
11350 if (SI->getOperand(1) == AI) continue;
11351 }
11352 isAddressTaken = true;
11353 break;
11354 }
11355
Chris Lattner36d3e322009-02-21 00:46:50 +000011356 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011357 return false;
11358 }
11359
Chris Lattner36d3e322009-02-21 00:46:50 +000011360 // If this load is a load from a GEP with a constant offset from an alloca,
11361 // then we don't want to sink it. In its present form, it will be
11362 // load [constant stack offset]. Sinking it will cause us to have to
11363 // materialize the stack addresses in each predecessor in a register only to
11364 // do a shared load from register in the successor.
11365 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11366 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11367 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11368 return false;
11369
Chris Lattner76c73142006-11-01 07:13:54 +000011370 return true;
11371}
11372
Chris Lattner751a3622009-11-01 20:04:24 +000011373Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11374 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11375
11376 // When processing loads, we need to propagate two bits of information to the
11377 // sunk load: whether it is volatile, and what its alignment is. We currently
11378 // don't sink loads when some have their alignment specified and some don't.
11379 // visitLoadInst will propagate an alignment onto the load when TD is around,
11380 // and if TD isn't around, we can't handle the mixed case.
11381 bool isVolatile = FirstLI->isVolatile();
11382 unsigned LoadAlignment = FirstLI->getAlignment();
11383
11384 // We can't sink the load if the loaded value could be modified between the
11385 // load and the PHI.
11386 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11387 !isSafeAndProfitableToSinkLoad(FirstLI))
11388 return 0;
11389
11390 // If the PHI is of volatile loads and the load block has multiple
11391 // successors, sinking it would remove a load of the volatile value from
11392 // the path through the other successor.
11393 if (isVolatile &&
11394 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11395 return 0;
11396
11397 // Check to see if all arguments are the same operation.
11398 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11399 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11400 if (!LI || !LI->hasOneUse())
11401 return 0;
11402
11403 // We can't sink the load if the loaded value could be modified between
11404 // the load and the PHI.
11405 if (LI->isVolatile() != isVolatile ||
11406 LI->getParent() != PN.getIncomingBlock(i) ||
11407 !isSafeAndProfitableToSinkLoad(LI))
11408 return 0;
11409
11410 // If some of the loads have an alignment specified but not all of them,
11411 // we can't do the transformation.
11412 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11413 return 0;
11414
Chris Lattnera664bb72009-11-01 20:07:07 +000011415 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011416
11417 // If the PHI is of volatile loads and the load block has multiple
11418 // successors, sinking it would remove a load of the volatile value from
11419 // the path through the other successor.
11420 if (isVolatile &&
11421 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11422 return 0;
11423 }
11424
11425 // Okay, they are all the same operation. Create a new PHI node of the
11426 // correct type, and PHI together all of the LHS's of the instructions.
11427 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11428 PN.getName()+".in");
11429 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11430
11431 Value *InVal = FirstLI->getOperand(0);
11432 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11433
11434 // Add all operands to the new PHI.
11435 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11436 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11437 if (NewInVal != InVal)
11438 InVal = 0;
11439 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11440 }
11441
11442 Value *PhiVal;
11443 if (InVal) {
11444 // The new PHI unions all of the same values together. This is really
11445 // common, so we handle it intelligently here for compile-time speed.
11446 PhiVal = InVal;
11447 delete NewPN;
11448 } else {
11449 InsertNewInstBefore(NewPN, PN);
11450 PhiVal = NewPN;
11451 }
11452
11453 // If this was a volatile load that we are merging, make sure to loop through
11454 // and mark all the input loads as non-volatile. If we don't do this, we will
11455 // insert a new volatile load and the old ones will not be deletable.
11456 if (isVolatile)
11457 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11458 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11459
11460 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11461}
11462
Chris Lattner9fe38862003-06-19 17:00:31 +000011463
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011464
11465/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11466/// operator and they all are only used by the PHI, PHI together their
11467/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011468Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11469 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11470
Chris Lattner751a3622009-11-01 20:04:24 +000011471 if (isa<GetElementPtrInst>(FirstInst))
11472 return FoldPHIArgGEPIntoPHI(PN);
11473 if (isa<LoadInst>(FirstInst))
11474 return FoldPHIArgLoadIntoPHI(PN);
11475
Chris Lattnerbac32862004-11-14 19:13:23 +000011476 // Scan the instruction, looking for input operations that can be folded away.
11477 // If all input operands to the phi are the same instruction (e.g. a cast from
11478 // the same type or "+42") we can pull the operation through the PHI, reducing
11479 // code size and simplifying code.
11480 Constant *ConstantOp = 0;
11481 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011482
Chris Lattnerbac32862004-11-14 19:13:23 +000011483 if (isa<CastInst>(FirstInst)) {
11484 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011485
11486 // Be careful about transforming integer PHIs. We don't want to pessimize
11487 // the code by turning an i32 into an i1293.
11488 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011489 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011490 return 0;
11491 }
Reid Spencer832254e2007-02-02 02:16:23 +000011492 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011493 // Can fold binop, compare or shift here if the RHS is a constant,
11494 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011495 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011496 if (ConstantOp == 0)
11497 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011498 } else {
11499 return 0; // Cannot fold this operation.
11500 }
11501
11502 // Check to see if all arguments are the same operation.
11503 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011504 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11505 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011506 return 0;
11507 if (CastSrcTy) {
11508 if (I->getOperand(0)->getType() != CastSrcTy)
11509 return 0; // Cast operation must match.
11510 } else if (I->getOperand(1) != ConstantOp) {
11511 return 0;
11512 }
11513 }
11514
11515 // Okay, they are all the same operation. Create a new PHI node of the
11516 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011517 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11518 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011519 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011520
11521 Value *InVal = FirstInst->getOperand(0);
11522 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011523
11524 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011525 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11526 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11527 if (NewInVal != InVal)
11528 InVal = 0;
11529 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11530 }
11531
11532 Value *PhiVal;
11533 if (InVal) {
11534 // The new PHI unions all of the same values together. This is really
11535 // common, so we handle it intelligently here for compile-time speed.
11536 PhiVal = InVal;
11537 delete NewPN;
11538 } else {
11539 InsertNewInstBefore(NewPN, PN);
11540 PhiVal = NewPN;
11541 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011542
Chris Lattnerbac32862004-11-14 19:13:23 +000011543 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011544 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011545 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011546
Chris Lattner54545ac2008-04-29 17:13:43 +000011547 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011548 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011549
Chris Lattner751a3622009-11-01 20:04:24 +000011550 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11551 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11552 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011553}
Chris Lattnera1be5662002-05-02 17:06:02 +000011554
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011555/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11556/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011557static bool DeadPHICycle(PHINode *PN,
11558 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011559 if (PN->use_empty()) return true;
11560 if (!PN->hasOneUse()) return false;
11561
11562 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011563 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011564 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011565
11566 // Don't scan crazily complex things.
11567 if (PotentiallyDeadPHIs.size() == 16)
11568 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011569
11570 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11571 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011572
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011573 return false;
11574}
11575
Chris Lattnercf5008a2007-11-06 21:52:06 +000011576/// PHIsEqualValue - Return true if this phi node is always equal to
11577/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11578/// z = some value; x = phi (y, z); y = phi (x, z)
11579static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11580 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11581 // See if we already saw this PHI node.
11582 if (!ValueEqualPHIs.insert(PN))
11583 return true;
11584
11585 // Don't scan crazily complex things.
11586 if (ValueEqualPHIs.size() == 16)
11587 return false;
11588
11589 // Scan the operands to see if they are either phi nodes or are equal to
11590 // the value.
11591 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11592 Value *Op = PN->getIncomingValue(i);
11593 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11594 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11595 return false;
11596 } else if (Op != NonPhiInVal)
11597 return false;
11598 }
11599
11600 return true;
11601}
11602
11603
Chris Lattner9956c052009-11-08 19:23:30 +000011604namespace {
11605struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011606 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011607 unsigned Shift; // The amount shifted.
11608 Instruction *Inst; // The trunc instruction.
11609
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011610 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11611 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011612
11613 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011614 if (PHIId < RHS.PHIId) return true;
11615 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011616 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011617 if (Shift > RHS.Shift) return false;
11618 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011619 RHS.Inst->getType()->getPrimitiveSizeInBits();
11620 }
11621};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011622
11623struct LoweredPHIRecord {
11624 PHINode *PN; // The PHI that was lowered.
11625 unsigned Shift; // The amount shifted.
11626 unsigned Width; // The width extracted.
11627
11628 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11629 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11630
11631 // Ctor form used by DenseMap.
11632 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11633 : PN(pn), Shift(Sh), Width(0) {}
11634};
11635}
11636
11637namespace llvm {
11638 template<>
11639 struct DenseMapInfo<LoweredPHIRecord> {
11640 static inline LoweredPHIRecord getEmptyKey() {
11641 return LoweredPHIRecord(0, 0);
11642 }
11643 static inline LoweredPHIRecord getTombstoneKey() {
11644 return LoweredPHIRecord(0, 1);
11645 }
11646 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11647 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11648 (Val.Width>>3);
11649 }
11650 static bool isEqual(const LoweredPHIRecord &LHS,
11651 const LoweredPHIRecord &RHS) {
11652 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11653 LHS.Width == RHS.Width;
11654 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011655 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011656 template <>
11657 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011658}
11659
11660
11661/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11662/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11663/// so, we split the PHI into the various pieces being extracted. This sort of
11664/// thing is introduced when SROA promotes an aggregate to large integer values.
11665///
11666/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11667/// inttoptr. We should produce new PHIs in the right type.
11668///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011669Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11670 // PHIUsers - Keep track of all of the truncated values extracted from a set
11671 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011672 SmallVector<PHIUsageRecord, 16> PHIUsers;
11673
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011674 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11675 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11676 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11677 // check the uses of (to ensure they are all extracts).
11678 SmallVector<PHINode*, 8> PHIsToSlice;
11679 SmallPtrSet<PHINode*, 8> PHIsInspected;
11680
11681 PHIsToSlice.push_back(&FirstPhi);
11682 PHIsInspected.insert(&FirstPhi);
11683
11684 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11685 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011686
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011687 // Scan the input list of the PHI. If any input is an invoke, and if the
11688 // input is defined in the predecessor, then we won't be split the critical
11689 // edge which is required to insert a truncate. Because of this, we have to
11690 // bail out.
11691 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11692 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11693 if (II == 0) continue;
11694 if (II->getParent() != PN->getIncomingBlock(i))
11695 continue;
11696
11697 // If we have a phi, and if it's directly in the predecessor, then we have
11698 // a critical edge where we need to put the truncate. Since we can't
11699 // split the edge in instcombine, we have to bail out.
11700 return 0;
11701 }
11702
11703
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011704 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11705 UI != E; ++UI) {
11706 Instruction *User = cast<Instruction>(*UI);
11707
11708 // If the user is a PHI, inspect its uses recursively.
11709 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11710 if (PHIsInspected.insert(UserPN))
11711 PHIsToSlice.push_back(UserPN);
11712 continue;
11713 }
11714
11715 // Truncates are always ok.
11716 if (isa<TruncInst>(User)) {
11717 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11718 continue;
11719 }
11720
11721 // Otherwise it must be a lshr which can only be used by one trunc.
11722 if (User->getOpcode() != Instruction::LShr ||
11723 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11724 !isa<ConstantInt>(User->getOperand(1)))
11725 return 0;
11726
11727 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11728 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011729 }
Chris Lattner9956c052009-11-08 19:23:30 +000011730 }
11731
11732 // If we have no users, they must be all self uses, just nuke the PHI.
11733 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011734 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011735
11736 // If this phi node is transformable, create new PHIs for all the pieces
11737 // extracted out of it. First, sort the users by their offset and size.
11738 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11739
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011740 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11741 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11742 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11743 );
Chris Lattner9956c052009-11-08 19:23:30 +000011744
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011745 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11746 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011747 DenseMap<BasicBlock*, Value*> PredValues;
11748
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011749 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11750 // introduce redundant PHIs.
11751 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11752
11753 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11754 unsigned PHIId = PHIUsers[UserI].PHIId;
11755 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011756 unsigned Offset = PHIUsers[UserI].Shift;
11757 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011758
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011759 PHINode *EltPHI;
11760
11761 // If we've already lowered a user like this, reuse the previously lowered
11762 // value.
11763 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011764
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011765 // Otherwise, Create the new PHI node for this user.
11766 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11767 assert(EltPHI->getType() != PN->getType() &&
11768 "Truncate didn't shrink phi?");
11769
11770 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11771 BasicBlock *Pred = PN->getIncomingBlock(i);
11772 Value *&PredVal = PredValues[Pred];
11773
11774 // If we already have a value for this predecessor, reuse it.
11775 if (PredVal) {
11776 EltPHI->addIncoming(PredVal, Pred);
11777 continue;
11778 }
Chris Lattner9956c052009-11-08 19:23:30 +000011779
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011780 // Handle the PHI self-reuse case.
11781 Value *InVal = PN->getIncomingValue(i);
11782 if (InVal == PN) {
11783 PredVal = EltPHI;
11784 EltPHI->addIncoming(PredVal, Pred);
11785 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011786 }
11787
11788 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011789 // If the incoming value was a PHI, and if it was one of the PHIs we
11790 // already rewrote it, just use the lowered value.
11791 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11792 PredVal = Res;
11793 EltPHI->addIncoming(PredVal, Pred);
11794 continue;
11795 }
11796 }
11797
11798 // Otherwise, do an extract in the predecessor.
11799 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11800 Value *Res = InVal;
11801 if (Offset)
11802 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11803 Offset), "extract");
11804 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11805 PredVal = Res;
11806 EltPHI->addIncoming(Res, Pred);
11807
11808 // If the incoming value was a PHI, and if it was one of the PHIs we are
11809 // rewriting, we will ultimately delete the code we inserted. This
11810 // means we need to revisit that PHI to make sure we extract out the
11811 // needed piece.
11812 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11813 if (PHIsInspected.count(OldInVal)) {
11814 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11815 OldInVal)-PHIsToSlice.begin();
11816 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11817 cast<Instruction>(Res)));
11818 ++UserE;
11819 }
Chris Lattner9956c052009-11-08 19:23:30 +000011820 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011821 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011822
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011823 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11824 << *EltPHI << '\n');
11825 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011826 }
Chris Lattner9956c052009-11-08 19:23:30 +000011827
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011828 // Replace the use of this piece with the PHI node.
11829 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011830 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011831
11832 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11833 // with undefs.
11834 Value *Undef = UndefValue::get(FirstPhi.getType());
11835 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11836 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11837 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011838}
11839
Chris Lattner473945d2002-05-06 18:06:38 +000011840// PHINode simplification
11841//
Chris Lattner7e708292002-06-25 16:13:24 +000011842Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011843 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011844 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011845
Owen Anderson7e057142006-07-10 22:03:18 +000011846 if (Value *V = PN.hasConstantValue())
11847 return ReplaceInstUsesWith(PN, V);
11848
Owen Anderson7e057142006-07-10 22:03:18 +000011849 // If all PHI operands are the same operation, pull them through the PHI,
11850 // reducing code size.
11851 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011852 isa<Instruction>(PN.getIncomingValue(1)) &&
11853 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11854 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11855 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11856 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011857 PN.getIncomingValue(0)->hasOneUse())
11858 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11859 return Result;
11860
11861 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11862 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11863 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011864 if (PN.hasOneUse()) {
11865 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11866 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011867 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011868 PotentiallyDeadPHIs.insert(&PN);
11869 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011870 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011871 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011872
11873 // If this phi has a single use, and if that use just computes a value for
11874 // the next iteration of a loop, delete the phi. This occurs with unused
11875 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11876 // common case here is good because the only other things that catch this
11877 // are induction variable analysis (sometimes) and ADCE, which is only run
11878 // late.
11879 if (PHIUser->hasOneUse() &&
11880 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11881 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011882 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011883 }
11884 }
Owen Anderson7e057142006-07-10 22:03:18 +000011885
Chris Lattnercf5008a2007-11-06 21:52:06 +000011886 // We sometimes end up with phi cycles that non-obviously end up being the
11887 // same value, for example:
11888 // z = some value; x = phi (y, z); y = phi (x, z)
11889 // where the phi nodes don't necessarily need to be in the same block. Do a
11890 // quick check to see if the PHI node only contains a single non-phi value, if
11891 // so, scan to see if the phi cycle is actually equal to that value.
11892 {
11893 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11894 // Scan for the first non-phi operand.
11895 while (InValNo != NumOperandVals &&
11896 isa<PHINode>(PN.getIncomingValue(InValNo)))
11897 ++InValNo;
11898
11899 if (InValNo != NumOperandVals) {
11900 Value *NonPhiInVal = PN.getOperand(InValNo);
11901
11902 // Scan the rest of the operands to see if there are any conflicts, if so
11903 // there is no need to recursively scan other phis.
11904 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11905 Value *OpVal = PN.getIncomingValue(InValNo);
11906 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11907 break;
11908 }
11909
11910 // If we scanned over all operands, then we have one unique value plus
11911 // phi values. Scan PHI nodes to see if they all merge in each other or
11912 // the value.
11913 if (InValNo == NumOperandVals) {
11914 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11915 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11916 return ReplaceInstUsesWith(PN, NonPhiInVal);
11917 }
11918 }
11919 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011920
Dan Gohman5b097012009-10-31 14:22:52 +000011921 // If there are multiple PHIs, sort their operands so that they all list
11922 // the blocks in the same order. This will help identical PHIs be eliminated
11923 // by other passes. Other passes shouldn't depend on this for correctness
11924 // however.
11925 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11926 if (&PN != FirstPN)
11927 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011928 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011929 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11930 if (BBA != BBB) {
11931 Value *VA = PN.getIncomingValue(i);
11932 unsigned j = PN.getBasicBlockIndex(BBB);
11933 Value *VB = PN.getIncomingValue(j);
11934 PN.setIncomingBlock(i, BBB);
11935 PN.setIncomingValue(i, VB);
11936 PN.setIncomingBlock(j, BBA);
11937 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011938 // NOTE: Instcombine normally would want us to "return &PN" if we
11939 // modified any of the operands of an instruction. However, since we
11940 // aren't adding or removing uses (just rearranging them) we don't do
11941 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011942 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011943 }
11944
Chris Lattner9956c052009-11-08 19:23:30 +000011945 // If this is an integer PHI and we know that it has an illegal type, see if
11946 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11947 // PHI into the various pieces being extracted. This sort of thing is
11948 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011949 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000011950 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
11951 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
11952 return Res;
11953
Chris Lattner60921c92003-12-19 05:58:40 +000011954 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000011955}
11956
Chris Lattner7e708292002-06-25 16:13:24 +000011957Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000011958 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
11959
11960 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
11961 return ReplaceInstUsesWith(GEP, V);
11962
Chris Lattner620ce142004-05-07 22:09:22 +000011963 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011964
Chris Lattnere87597f2004-10-16 18:11:37 +000011965 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011966 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000011967
Chris Lattner28977af2004-04-05 01:30:19 +000011968 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000011969 if (TD) {
11970 bool MadeChange = false;
11971 unsigned PtrSize = TD->getPointerSizeInBits();
11972
11973 gep_type_iterator GTI = gep_type_begin(GEP);
11974 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11975 I != E; ++I, ++GTI) {
11976 if (!isa<SequentialType>(*GTI)) continue;
11977
Chris Lattnercb69a4e2004-04-07 18:38:20 +000011978 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000011979 // to what we need. If narrower, sign-extend it to what we need. This
11980 // explicit cast can make subsequent optimizations more obvious.
11981 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000011982 if (OpBits == PtrSize)
11983 continue;
11984
Chris Lattner2345d1d2009-08-30 20:01:10 +000011985 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000011986 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000011987 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000011988 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000011989 }
Chris Lattner28977af2004-04-05 01:30:19 +000011990
Chris Lattner90ac28c2002-08-02 19:29:35 +000011991 // Combine Indices - If the source pointer to this getelementptr instruction
11992 // is a getelementptr instruction, combine the indices of the two
11993 // getelementptr instructions into a single instruction.
11994 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011995 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000011996 // Note that if our source is a gep chain itself that we wait for that
11997 // chain to be resolved before we perform this transformation. This
11998 // avoids us creating a TON of code in some cases.
11999 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012000 if (GetElementPtrInst *SrcGEP =
12001 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
12002 if (SrcGEP->getNumOperands() == 2)
12003 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000012004
Chris Lattner72588fc2007-02-15 22:48:32 +000012005 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000012006
12007 // Find out whether the last index in the source GEP is a sequential idx.
12008 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000012009 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12010 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000012011 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012012
Chris Lattner90ac28c2002-08-02 19:29:35 +000012013 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000012014 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000012015 // Replace: gep (gep %P, long B), long A, ...
12016 // With: T = long A+B; gep %P, T, ...
12017 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012018 Value *Sum;
12019 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12020 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000012021 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012022 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000012023 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012024 Sum = SO1;
12025 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000012026 // If they aren't the same type, then the input hasn't been processed
12027 // by the loop above yet (which canonicalizes sequential index types to
12028 // intptr_t). Just avoid transforming this until the input has been
12029 // normalized.
12030 if (SO1->getType() != GO1->getType())
12031 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012032 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000012033 }
Chris Lattner620ce142004-05-07 22:09:22 +000012034
Chris Lattnerab984842009-08-30 05:30:55 +000012035 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012036 if (Src->getNumOperands() == 2) {
12037 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000012038 GEP.setOperand(1, Sum);
12039 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000012040 }
Chris Lattnerab984842009-08-30 05:30:55 +000012041 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012042 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000012043 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000012044 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000012045 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012046 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000012047 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000012048 Indices.append(Src->op_begin()+1, Src->op_end());
12049 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000012050 }
12051
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012052 if (!Indices.empty())
12053 return (cast<GEPOperator>(&GEP)->isInBounds() &&
12054 Src->isInBounds()) ?
12055 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12056 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012057 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000012058 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000012059 }
12060
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012061 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12062 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000012063 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000012064
Chris Lattner2de23192009-08-30 20:38:21 +000012065 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
12066 // want to change the gep until the bitcasts are eliminated.
12067 if (getBitCastOperand(X)) {
12068 Worklist.AddValue(PtrOp);
12069 return 0;
12070 }
12071
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012072 bool HasZeroPointerIndex = false;
12073 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12074 HasZeroPointerIndex = C->isZero();
12075
Chris Lattner963f4ba2009-08-30 20:36:46 +000012076 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12077 // into : GEP [10 x i8]* X, i32 0, ...
12078 //
12079 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12080 // into : GEP i8* X, ...
12081 //
12082 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000012083 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000012084 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12085 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012086 if (const ArrayType *CATy =
12087 dyn_cast<ArrayType>(CPTy->getElementType())) {
12088 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12089 if (CATy->getElementType() == XTy->getElementType()) {
12090 // -> GEP i8* X, ...
12091 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012092 return cast<GEPOperator>(&GEP)->isInBounds() ?
12093 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12094 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012095 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12096 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000012097 }
12098
12099 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012100 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000012101 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012102 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000012103 // At this point, we know that the cast source type is a pointer
12104 // to an array of the same type as the destination pointer
12105 // array. Because the array type is never stepped over (there
12106 // is a leading zero) we can fold the cast into this GEP.
12107 GEP.setOperand(0, X);
12108 return &GEP;
12109 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012110 }
12111 }
Chris Lattnereed48272005-09-13 00:40:14 +000012112 } else if (GEP.getNumOperands() == 2) {
12113 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012114 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12115 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000012116 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12117 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012118 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000012119 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12120 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000012121 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012122 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012123 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012124 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12125 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012126 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012127 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012128 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012129 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000012130
12131 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012132 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000012133 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012134 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000012135
Owen Anderson1d0be152009-08-13 21:58:54 +000012136 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000012137 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000012138 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012139
12140 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
12141 // allow either a mul, shift, or constant here.
12142 Value *NewIdx = 0;
12143 ConstantInt *Scale = 0;
12144 if (ArrayEltSize == 1) {
12145 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000012146 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012147 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012148 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012149 Scale = CI;
12150 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12151 if (Inst->getOpcode() == Instruction::Shl &&
12152 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000012153 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12154 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000012155 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000012156 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012157 NewIdx = Inst->getOperand(0);
12158 } else if (Inst->getOpcode() == Instruction::Mul &&
12159 isa<ConstantInt>(Inst->getOperand(1))) {
12160 Scale = cast<ConstantInt>(Inst->getOperand(1));
12161 NewIdx = Inst->getOperand(0);
12162 }
12163 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012164
Chris Lattner7835cdd2005-09-13 18:36:04 +000012165 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012166 // out, perform the transformation. Note, we don't know whether Scale is
12167 // signed or not. We'll use unsigned version of division/modulo
12168 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000012169 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012170 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012171 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012172 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000012173 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000012174 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12175 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012176 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000012177 }
12178
12179 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000012180 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012181 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012182 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012183 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12184 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12185 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012186 // The NewGEP must be pointer typed, so must the old one -> BitCast
12187 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012188 }
12189 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012190 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012191 }
Chris Lattner58407792009-01-09 04:53:57 +000012192
Chris Lattner46cd5a12009-01-09 05:44:56 +000012193 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000012194 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000012195 /// Y = gep X, <...constant indices...>
12196 /// into a gep of the original struct. This is important for SROA and alias
12197 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000012198 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012199 if (TD &&
12200 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012201 // Determine how much the GEP moves the pointer. We are guaranteed to get
12202 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000012203 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000012204 int64_t Offset = OffsetV->getSExtValue();
12205
12206 // If this GEP instruction doesn't move the pointer, just replace the GEP
12207 // with a bitcast of the real input to the dest type.
12208 if (Offset == 0) {
12209 // If the bitcast is of an allocation, and the allocation will be
12210 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000012211 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000012212 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012213 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12214 if (Instruction *I = visitBitCast(*BCI)) {
12215 if (I != BCI) {
12216 I->takeName(BCI);
12217 BCI->getParent()->getInstList().insert(BCI, I);
12218 ReplaceInstUsesWith(*BCI, I);
12219 }
12220 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012221 }
Chris Lattner58407792009-01-09 04:53:57 +000012222 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012223 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012224 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012225
12226 // Otherwise, if the offset is non-zero, we need to find out if there is a
12227 // field at Offset in 'A's type. If so, we can pull the cast through the
12228 // GEP.
12229 SmallVector<Value*, 8> NewIndices;
12230 const Type *InTy =
12231 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000012232 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012233 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12234 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12235 NewIndices.end()) :
12236 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12237 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012238
12239 if (NGEP->getType() == GEP.getType())
12240 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012241 NGEP->takeName(&GEP);
12242 return new BitCastInst(NGEP, GEP.getType());
12243 }
Chris Lattner58407792009-01-09 04:53:57 +000012244 }
12245 }
12246
Chris Lattner8a2a3112001-12-14 16:52:21 +000012247 return 0;
12248}
12249
Victor Hernandez7b929da2009-10-23 21:09:37 +000012250Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012251 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012252 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012253 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12254 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012255 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012256 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012257 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012258 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012259
Chris Lattner0864acf2002-11-04 16:18:53 +000012260 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012261 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012262 //
12263 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012264 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012265
12266 // Now that I is pointing to the first non-allocation-inst in the block,
12267 // insert our getelementptr instruction...
12268 //
Owen Anderson1d0be152009-08-13 21:58:54 +000012269 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012270 Value *Idx[2];
12271 Idx[0] = NullIdx;
12272 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012273 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12274 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012275
12276 // Now make everything use the getelementptr instead of the original
12277 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012278 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012279 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012280 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012281 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012282 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012283
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012284 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012285 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012286 // Note that we only do this for alloca's, because malloc should allocate
12287 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012288 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012289 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012290
12291 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12292 if (AI.getAlignment() == 0)
12293 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12294 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012295
Chris Lattner0864acf2002-11-04 16:18:53 +000012296 return 0;
12297}
12298
Victor Hernandez66284e02009-10-24 04:23:03 +000012299Instruction *InstCombiner::visitFree(Instruction &FI) {
12300 Value *Op = FI.getOperand(1);
12301
12302 // free undef -> unreachable.
12303 if (isa<UndefValue>(Op)) {
12304 // Insert a new store to null because we cannot modify the CFG here.
12305 new StoreInst(ConstantInt::getTrue(*Context),
12306 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12307 return EraseInstFromFunction(FI);
12308 }
12309
12310 // If we have 'free null' delete the instruction. This can happen in stl code
12311 // when lots of inlining happens.
12312 if (isa<ConstantPointerNull>(Op))
12313 return EraseInstFromFunction(FI);
12314
Victor Hernandez046e78c2009-10-26 23:43:48 +000012315 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012316 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012317 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12318 if (Op->hasOneUse() && CI->hasOneUse()) {
12319 EraseInstFromFunction(FI);
12320 EraseInstFromFunction(*CI);
12321 return EraseInstFromFunction(*cast<Instruction>(Op));
12322 }
12323 } else {
12324 // Op is a call to malloc
12325 if (Op->hasOneUse()) {
12326 EraseInstFromFunction(FI);
12327 return EraseInstFromFunction(*cast<Instruction>(Op));
12328 }
12329 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012330 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012331
12332 return 0;
12333}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012334
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012335/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012336static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012337 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012338 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012339 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000012340 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000012341
Mon P Wang6753f952009-02-07 22:19:29 +000012342 const PointerType *DestTy = cast<PointerType>(CI->getType());
12343 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012344 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012345
12346 // If the address spaces don't match, don't eliminate the cast.
12347 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12348 return 0;
12349
Chris Lattnerb89e0712004-07-13 01:49:43 +000012350 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012351
Reid Spencer42230162007-01-22 05:51:25 +000012352 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012353 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012354 // If the source is an array, the code below will not succeed. Check to
12355 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12356 // constants.
12357 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12358 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12359 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012360 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012361 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12362 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012363 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012364 SrcTy = cast<PointerType>(CastOp->getType());
12365 SrcPTy = SrcTy->getElementType();
12366 }
12367
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012368 if (IC.getTargetData() &&
12369 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012370 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012371 // Do not allow turning this into a load of an integer, which is then
12372 // casted to a pointer, this pessimizes pointer analysis a lot.
12373 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012374 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12375 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012376
Chris Lattnerf9527852005-01-31 04:50:46 +000012377 // Okay, we are casting from one integer or pointer type to another of
12378 // the same size. Instead of casting the pointer before the load, cast
12379 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012380 Value *NewLoad =
12381 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012382 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012383 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012384 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012385 }
12386 }
12387 return 0;
12388}
12389
Chris Lattner833b8a42003-06-26 05:06:25 +000012390Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12391 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012392
Dan Gohman9941f742007-07-20 16:34:21 +000012393 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012394 if (TD) {
12395 unsigned KnownAlign =
12396 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12397 if (KnownAlign >
12398 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12399 LI.getAlignment()))
12400 LI.setAlignment(KnownAlign);
12401 }
Dan Gohman9941f742007-07-20 16:34:21 +000012402
Chris Lattner963f4ba2009-08-30 20:36:46 +000012403 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012404 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012405 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012406 return Res;
12407
12408 // None of the following transforms are legal for volatile loads.
12409 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012410
Dan Gohman2276a7b2008-10-15 23:19:35 +000012411 // Do really simple store-to-load forwarding and load CSE, to catch cases
12412 // where there are several consequtive memory accesses to the same location,
12413 // separated by a few arithmetic operations.
12414 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012415 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12416 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012417
Chris Lattner878e4942009-10-22 06:25:11 +000012418 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012419 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12420 const Value *GEPI0 = GEPI->getOperand(0);
12421 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012422 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012423 // Insert a new store to null instruction before the load to indicate
12424 // that this code is not reachable. We do this instead of inserting
12425 // an unreachable instruction directly because we cannot modify the
12426 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012427 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012428 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012429 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012430 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012431 }
Chris Lattner37366c12005-05-01 04:24:53 +000012432
Chris Lattner878e4942009-10-22 06:25:11 +000012433 // load null/undef -> unreachable
12434 // TODO: Consider a target hook for valid address spaces for this xform.
12435 if (isa<UndefValue>(Op) ||
12436 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12437 // Insert a new store to null instruction before the load to indicate that
12438 // this code is not reachable. We do this instead of inserting an
12439 // unreachable instruction directly because we cannot modify the CFG.
12440 new StoreInst(UndefValue::get(LI.getType()),
12441 Constant::getNullValue(Op->getType()), &LI);
12442 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012443 }
Chris Lattner878e4942009-10-22 06:25:11 +000012444
12445 // Instcombine load (constantexpr_cast global) -> cast (load global)
12446 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12447 if (CE->isCast())
12448 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12449 return Res;
12450
Chris Lattner37366c12005-05-01 04:24:53 +000012451 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012452 // Change select and PHI nodes to select values instead of addresses: this
12453 // helps alias analysis out a lot, allows many others simplifications, and
12454 // exposes redundancy in the code.
12455 //
12456 // Note that we cannot do the transformation unless we know that the
12457 // introduced loads cannot trap! Something like this is valid as long as
12458 // the condition is always false: load (select bool %C, int* null, int* %G),
12459 // but it would not be valid if we transformed it to load from null
12460 // unconditionally.
12461 //
12462 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12463 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012464 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12465 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012466 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12467 SI->getOperand(1)->getName()+".val");
12468 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12469 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012470 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012471 }
12472
Chris Lattner684fe212004-09-23 15:46:00 +000012473 // load (select (cond, null, P)) -> load P
12474 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12475 if (C->isNullValue()) {
12476 LI.setOperand(0, SI->getOperand(2));
12477 return &LI;
12478 }
12479
12480 // load (select (cond, P, null)) -> load P
12481 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12482 if (C->isNullValue()) {
12483 LI.setOperand(0, SI->getOperand(1));
12484 return &LI;
12485 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012486 }
12487 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012488 return 0;
12489}
12490
Reid Spencer55af2b52007-01-19 21:20:31 +000012491/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012492/// when possible. This makes it generally easy to do alias analysis and/or
12493/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012494static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12495 User *CI = cast<User>(SI.getOperand(1));
12496 Value *CastOp = CI->getOperand(0);
12497
12498 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012499 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12500 if (SrcTy == 0) return 0;
12501
12502 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012503
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012504 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12505 return 0;
12506
Chris Lattner3914f722009-01-24 01:00:13 +000012507 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12508 /// to its first element. This allows us to handle things like:
12509 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12510 /// on 32-bit hosts.
12511 SmallVector<Value*, 4> NewGEPIndices;
12512
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012513 // If the source is an array, the code below will not succeed. Check to
12514 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12515 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012516 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12517 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012518 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012519 NewGEPIndices.push_back(Zero);
12520
12521 while (1) {
12522 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012523 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012524 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012525 NewGEPIndices.push_back(Zero);
12526 SrcPTy = STy->getElementType(0);
12527 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12528 NewGEPIndices.push_back(Zero);
12529 SrcPTy = ATy->getElementType();
12530 } else {
12531 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012532 }
Chris Lattner3914f722009-01-24 01:00:13 +000012533 }
12534
Owen Andersondebcb012009-07-29 22:17:13 +000012535 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012536 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012537
12538 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12539 return 0;
12540
Chris Lattner71759c42009-01-16 20:12:52 +000012541 // If the pointers point into different address spaces or if they point to
12542 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012543 if (!IC.getTargetData() ||
12544 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012545 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012546 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12547 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012548 return 0;
12549
12550 // Okay, we are casting from one integer or pointer type to another of
12551 // the same size. Instead of casting the pointer before
12552 // the store, cast the value to be stored.
12553 Value *NewCast;
12554 Value *SIOp0 = SI.getOperand(0);
12555 Instruction::CastOps opcode = Instruction::BitCast;
12556 const Type* CastSrcTy = SIOp0->getType();
12557 const Type* CastDstTy = SrcPTy;
12558 if (isa<PointerType>(CastDstTy)) {
12559 if (CastSrcTy->isInteger())
12560 opcode = Instruction::IntToPtr;
12561 } else if (isa<IntegerType>(CastDstTy)) {
12562 if (isa<PointerType>(SIOp0->getType()))
12563 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012564 }
Chris Lattner3914f722009-01-24 01:00:13 +000012565
12566 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12567 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012568 if (!NewGEPIndices.empty())
12569 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12570 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012571
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012572 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12573 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012574 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012575}
12576
Chris Lattner4aebaee2008-11-27 08:56:30 +000012577/// equivalentAddressValues - Test if A and B will obviously have the same
12578/// value. This includes recognizing that %t0 and %t1 will have the same
12579/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012580/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012581/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012582/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012583/// %t2 = load i32* %t1
12584///
12585static bool equivalentAddressValues(Value *A, Value *B) {
12586 // Test if the values are trivially equivalent.
12587 if (A == B) return true;
12588
12589 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012590 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12591 // its only used to compare two uses within the same basic block, which
12592 // means that they'll always either have the same value or one of them
12593 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012594 if (isa<BinaryOperator>(A) ||
12595 isa<CastInst>(A) ||
12596 isa<PHINode>(A) ||
12597 isa<GetElementPtrInst>(A))
12598 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012599 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012600 return true;
12601
12602 // Otherwise they may not be equivalent.
12603 return false;
12604}
12605
Dale Johannesen4945c652009-03-03 21:26:39 +000012606// If this instruction has two uses, one of which is a llvm.dbg.declare,
12607// return the llvm.dbg.declare.
12608DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12609 if (!V->hasNUses(2))
12610 return 0;
12611 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12612 UI != E; ++UI) {
12613 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12614 return DI;
12615 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12616 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12617 return DI;
12618 }
12619 }
12620 return 0;
12621}
12622
Chris Lattner2f503e62005-01-31 05:36:43 +000012623Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12624 Value *Val = SI.getOperand(0);
12625 Value *Ptr = SI.getOperand(1);
12626
Chris Lattner836692d2007-01-15 06:51:56 +000012627 // If the RHS is an alloca with a single use, zapify the store, making the
12628 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012629 // If the RHS is an alloca with a two uses, the other one being a
12630 // llvm.dbg.declare, zapify the store and the declare, making the
12631 // alloca dead. We must do this to prevent declare's from affecting
12632 // codegen.
12633 if (!SI.isVolatile()) {
12634 if (Ptr->hasOneUse()) {
12635 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012636 EraseInstFromFunction(SI);
12637 ++NumCombined;
12638 return 0;
12639 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012640 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12641 if (isa<AllocaInst>(GEP->getOperand(0))) {
12642 if (GEP->getOperand(0)->hasOneUse()) {
12643 EraseInstFromFunction(SI);
12644 ++NumCombined;
12645 return 0;
12646 }
12647 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12648 EraseInstFromFunction(*DI);
12649 EraseInstFromFunction(SI);
12650 ++NumCombined;
12651 return 0;
12652 }
12653 }
12654 }
12655 }
12656 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12657 EraseInstFromFunction(*DI);
12658 EraseInstFromFunction(SI);
12659 ++NumCombined;
12660 return 0;
12661 }
Chris Lattner836692d2007-01-15 06:51:56 +000012662 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012663
Dan Gohman9941f742007-07-20 16:34:21 +000012664 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012665 if (TD) {
12666 unsigned KnownAlign =
12667 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12668 if (KnownAlign >
12669 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12670 SI.getAlignment()))
12671 SI.setAlignment(KnownAlign);
12672 }
Dan Gohman9941f742007-07-20 16:34:21 +000012673
Dale Johannesenacb51a32009-03-03 01:43:03 +000012674 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012675 // stores to the same location, separated by a few arithmetic operations. This
12676 // situation often occurs with bitfield accesses.
12677 BasicBlock::iterator BBI = &SI;
12678 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12679 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012680 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012681 // Don't count debug info directives, lest they affect codegen,
12682 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12683 // It is necessary for correctness to skip those that feed into a
12684 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012685 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012686 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012687 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012688 continue;
12689 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012690
12691 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12692 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012693 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12694 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012695 ++NumDeadStore;
12696 ++BBI;
12697 EraseInstFromFunction(*PrevSI);
12698 continue;
12699 }
12700 break;
12701 }
12702
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012703 // If this is a load, we have to stop. However, if the loaded value is from
12704 // the pointer we're loading and is producing the pointer we're storing,
12705 // then *this* store is dead (X = load P; store X -> P).
12706 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012707 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12708 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012709 EraseInstFromFunction(SI);
12710 ++NumCombined;
12711 return 0;
12712 }
12713 // Otherwise, this is a load from some other location. Stores before it
12714 // may not be dead.
12715 break;
12716 }
12717
Chris Lattner9ca96412006-02-08 03:25:32 +000012718 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012719 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012720 break;
12721 }
12722
12723
12724 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012725
12726 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012727 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012728 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012729 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012730 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012731 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012732 ++NumCombined;
12733 }
12734 return 0; // Do not modify these!
12735 }
12736
12737 // store undef, Ptr -> noop
12738 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012739 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012740 ++NumCombined;
12741 return 0;
12742 }
12743
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012744 // If the pointer destination is a cast, see if we can fold the cast into the
12745 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012746 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012747 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12748 return Res;
12749 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012750 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012751 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12752 return Res;
12753
Chris Lattner408902b2005-09-12 23:23:25 +000012754
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012755 // If this store is the last instruction in the basic block (possibly
12756 // excepting debug info instructions and the pointer bitcasts that feed
12757 // into them), and if the block ends with an unconditional branch, try
12758 // to move it to the successor block.
12759 BBI = &SI;
12760 do {
12761 ++BBI;
12762 } while (isa<DbgInfoIntrinsic>(BBI) ||
12763 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012764 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012765 if (BI->isUnconditional())
12766 if (SimplifyStoreAtEndOfBlock(SI))
12767 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012768
Chris Lattner2f503e62005-01-31 05:36:43 +000012769 return 0;
12770}
12771
Chris Lattner3284d1f2007-04-15 00:07:55 +000012772/// SimplifyStoreAtEndOfBlock - Turn things like:
12773/// if () { *P = v1; } else { *P = v2 }
12774/// into a phi node with a store in the successor.
12775///
Chris Lattner31755a02007-04-15 01:02:18 +000012776/// Simplify things like:
12777/// *P = v1; if () { *P = v2; }
12778/// into a phi node with a store in the successor.
12779///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012780bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12781 BasicBlock *StoreBB = SI.getParent();
12782
12783 // Check to see if the successor block has exactly two incoming edges. If
12784 // so, see if the other predecessor contains a store to the same location.
12785 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012786 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012787
12788 // Determine whether Dest has exactly two predecessors and, if so, compute
12789 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012790 pred_iterator PI = pred_begin(DestBB);
12791 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012792 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012793 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012794 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012795 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012796 return false;
12797
12798 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012799 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012800 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012801 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012802 }
Chris Lattner31755a02007-04-15 01:02:18 +000012803 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012804 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012805
12806 // Bail out if all the relevant blocks aren't distinct (this can happen,
12807 // for example, if SI is in an infinite loop)
12808 if (StoreBB == DestBB || OtherBB == DestBB)
12809 return false;
12810
Chris Lattner31755a02007-04-15 01:02:18 +000012811 // Verify that the other block ends in a branch and is not otherwise empty.
12812 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012813 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012814 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012815 return false;
12816
Chris Lattner31755a02007-04-15 01:02:18 +000012817 // If the other block ends in an unconditional branch, check for the 'if then
12818 // else' case. there is an instruction before the branch.
12819 StoreInst *OtherStore = 0;
12820 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012821 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012822 // Skip over debugging info.
12823 while (isa<DbgInfoIntrinsic>(BBI) ||
12824 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12825 if (BBI==OtherBB->begin())
12826 return false;
12827 --BBI;
12828 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012829 // If this isn't a store, isn't a store to the same location, or if the
12830 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012831 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012832 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12833 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012834 return false;
12835 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012836 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012837 // destinations is StoreBB, then we have the if/then case.
12838 if (OtherBr->getSuccessor(0) != StoreBB &&
12839 OtherBr->getSuccessor(1) != StoreBB)
12840 return false;
12841
12842 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012843 // if/then triangle. See if there is a store to the same ptr as SI that
12844 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012845 for (;; --BBI) {
12846 // Check to see if we find the matching store.
12847 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012848 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12849 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012850 return false;
12851 break;
12852 }
Eli Friedman6903a242008-06-13 22:02:12 +000012853 // If we find something that may be using or overwriting the stored
12854 // value, or if we run out of instructions, we can't do the xform.
12855 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012856 BBI == OtherBB->begin())
12857 return false;
12858 }
12859
12860 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012861 // make sure nothing reads or overwrites the stored value in
12862 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012863 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12864 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012865 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012866 return false;
12867 }
12868 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012869
Chris Lattner31755a02007-04-15 01:02:18 +000012870 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012871 Value *MergedVal = OtherStore->getOperand(0);
12872 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012873 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012874 PN->reserveOperandSpace(2);
12875 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012876 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12877 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012878 }
12879
12880 // Advance to a place where it is safe to insert the new store and
12881 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012882 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012883 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012884 OtherStore->isVolatile(),
12885 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012886
12887 // Nuke the old stores.
12888 EraseInstFromFunction(SI);
12889 EraseInstFromFunction(*OtherStore);
12890 ++NumCombined;
12891 return true;
12892}
12893
Chris Lattner2f503e62005-01-31 05:36:43 +000012894
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012895Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12896 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012897 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012898 BasicBlock *TrueDest;
12899 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012900 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012901 !isa<Constant>(X)) {
12902 // Swap Destinations and condition...
12903 BI.setCondition(X);
12904 BI.setSuccessor(0, FalseDest);
12905 BI.setSuccessor(1, TrueDest);
12906 return &BI;
12907 }
12908
Reid Spencere4d87aa2006-12-23 06:05:41 +000012909 // Cannonicalize fcmp_one -> fcmp_oeq
12910 FCmpInst::Predicate FPred; Value *Y;
12911 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012912 TrueDest, FalseDest)) &&
12913 BI.getCondition()->hasOneUse())
12914 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12915 FPred == FCmpInst::FCMP_OGE) {
12916 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12917 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12918
12919 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012920 BI.setSuccessor(0, FalseDest);
12921 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012922 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012923 return &BI;
12924 }
12925
12926 // Cannonicalize icmp_ne -> icmp_eq
12927 ICmpInst::Predicate IPred;
12928 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012929 TrueDest, FalseDest)) &&
12930 BI.getCondition()->hasOneUse())
12931 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12932 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12933 IPred == ICmpInst::ICMP_SGE) {
12934 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12935 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12936 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012937 BI.setSuccessor(0, FalseDest);
12938 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012939 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012940 return &BI;
12941 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012942
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012943 return 0;
12944}
Chris Lattner0864acf2002-11-04 16:18:53 +000012945
Chris Lattner46238a62004-07-03 00:26:11 +000012946Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12947 Value *Cond = SI.getCondition();
12948 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12949 if (I->getOpcode() == Instruction::Add)
12950 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12951 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12952 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012953 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000012954 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000012955 AddRHS));
12956 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000012957 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000012958 return &SI;
12959 }
12960 }
12961 return 0;
12962}
12963
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012964Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012965 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012966
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012967 if (!EV.hasIndices())
12968 return ReplaceInstUsesWith(EV, Agg);
12969
12970 if (Constant *C = dyn_cast<Constant>(Agg)) {
12971 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012972 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012973
12974 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012975 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012976
12977 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12978 // Extract the element indexed by the first index out of the constant
12979 Value *V = C->getOperand(*EV.idx_begin());
12980 if (EV.getNumIndices() > 1)
12981 // Extract the remaining indices out of the constant indexed by the
12982 // first index
12983 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12984 else
12985 return ReplaceInstUsesWith(EV, V);
12986 }
12987 return 0; // Can't handle other constants
12988 }
12989 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12990 // We're extracting from an insertvalue instruction, compare the indices
12991 const unsigned *exti, *exte, *insi, *inse;
12992 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12993 exte = EV.idx_end(), inse = IV->idx_end();
12994 exti != exte && insi != inse;
12995 ++exti, ++insi) {
12996 if (*insi != *exti)
12997 // The insert and extract both reference distinctly different elements.
12998 // This means the extract is not influenced by the insert, and we can
12999 // replace the aggregate operand of the extract with the aggregate
13000 // operand of the insert. i.e., replace
13001 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13002 // %E = extractvalue { i32, { i32 } } %I, 0
13003 // with
13004 // %E = extractvalue { i32, { i32 } } %A, 0
13005 return ExtractValueInst::Create(IV->getAggregateOperand(),
13006 EV.idx_begin(), EV.idx_end());
13007 }
13008 if (exti == exte && insi == inse)
13009 // Both iterators are at the end: Index lists are identical. Replace
13010 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13011 // %C = extractvalue { i32, { i32 } } %B, 1, 0
13012 // with "i32 42"
13013 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13014 if (exti == exte) {
13015 // The extract list is a prefix of the insert list. i.e. replace
13016 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13017 // %E = extractvalue { i32, { i32 } } %I, 1
13018 // with
13019 // %X = extractvalue { i32, { i32 } } %A, 1
13020 // %E = insertvalue { i32 } %X, i32 42, 0
13021 // by switching the order of the insert and extract (though the
13022 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000013023 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13024 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013025 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13026 insi, inse);
13027 }
13028 if (insi == inse)
13029 // The insert list is a prefix of the extract list
13030 // We can simply remove the common indices from the extract and make it
13031 // operate on the inserted value instead of the insertvalue result.
13032 // i.e., replace
13033 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13034 // %E = extractvalue { i32, { i32 } } %I, 1, 0
13035 // with
13036 // %E extractvalue { i32 } { i32 42 }, 0
13037 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
13038 exti, exte);
13039 }
Chris Lattner7e606e22009-11-09 07:07:56 +000013040 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13041 // We're extracting from an intrinsic, see if we're the only user, which
13042 // allows us to simplify multiple result intrinsics to simpler things that
13043 // just get one value..
13044 if (II->hasOneUse()) {
13045 // Check if we're grabbing the overflow bit or the result of a 'with
13046 // overflow' intrinsic. If it's the latter we can remove the intrinsic
13047 // and replace it with a traditional binary instruction.
13048 switch (II->getIntrinsicID()) {
13049 case Intrinsic::uadd_with_overflow:
13050 case Intrinsic::sadd_with_overflow:
13051 if (*EV.idx_begin() == 0) { // Normal result.
13052 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13053 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13054 EraseInstFromFunction(*II);
13055 return BinaryOperator::CreateAdd(LHS, RHS);
13056 }
13057 break;
13058 case Intrinsic::usub_with_overflow:
13059 case Intrinsic::ssub_with_overflow:
13060 if (*EV.idx_begin() == 0) { // Normal result.
13061 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13062 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13063 EraseInstFromFunction(*II);
13064 return BinaryOperator::CreateSub(LHS, RHS);
13065 }
13066 break;
13067 case Intrinsic::umul_with_overflow:
13068 case Intrinsic::smul_with_overflow:
13069 if (*EV.idx_begin() == 0) { // Normal result.
13070 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13071 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13072 EraseInstFromFunction(*II);
13073 return BinaryOperator::CreateMul(LHS, RHS);
13074 }
13075 break;
13076 default:
13077 break;
13078 }
13079 }
13080 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013081 // Can't simplify extracts from other values. Note that nested extracts are
13082 // already simplified implicitely by the above (extract ( extract (insert) )
13083 // will be translated into extract ( insert ( extract ) ) first and then just
13084 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013085 return 0;
13086}
13087
Chris Lattner220b0cf2006-03-05 00:22:33 +000013088/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13089/// is to leave as a vector operation.
13090static bool CheapToScalarize(Value *V, bool isConstant) {
13091 if (isa<ConstantAggregateZero>(V))
13092 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013093 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000013094 if (isConstant) return true;
13095 // If all elts are the same, we can extract.
13096 Constant *Op0 = C->getOperand(0);
13097 for (unsigned i = 1; i < C->getNumOperands(); ++i)
13098 if (C->getOperand(i) != Op0)
13099 return false;
13100 return true;
13101 }
13102 Instruction *I = dyn_cast<Instruction>(V);
13103 if (!I) return false;
13104
13105 // Insert element gets simplified to the inserted element or is deleted if
13106 // this is constant idx extract element and its a constant idx insertelt.
13107 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13108 isa<ConstantInt>(I->getOperand(2)))
13109 return true;
13110 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13111 return true;
13112 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13113 if (BO->hasOneUse() &&
13114 (CheapToScalarize(BO->getOperand(0), isConstant) ||
13115 CheapToScalarize(BO->getOperand(1), isConstant)))
13116 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000013117 if (CmpInst *CI = dyn_cast<CmpInst>(I))
13118 if (CI->hasOneUse() &&
13119 (CheapToScalarize(CI->getOperand(0), isConstant) ||
13120 CheapToScalarize(CI->getOperand(1), isConstant)))
13121 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000013122
13123 return false;
13124}
13125
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000013126/// Read and decode a shufflevector mask.
13127///
13128/// It turns undef elements into values that are larger than the number of
13129/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000013130static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13131 unsigned NElts = SVI->getType()->getNumElements();
13132 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13133 return std::vector<unsigned>(NElts, 0);
13134 if (isa<UndefValue>(SVI->getOperand(2)))
13135 return std::vector<unsigned>(NElts, 2*NElts);
13136
13137 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013138 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000013139 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13140 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000013141 Result.push_back(NElts*2); // undef -> 8
13142 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000013143 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000013144 return Result;
13145}
13146
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013147/// FindScalarElement - Given a vector and an element number, see if the scalar
13148/// value is already around as a register, for example if it were inserted then
13149/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000013150static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013151 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013152 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13153 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000013154 unsigned Width = PTy->getNumElements();
13155 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013156 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013157
13158 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013159 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013160 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000013161 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000013162 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013163 return CP->getOperand(EltNo);
13164 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13165 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000013166 if (!isa<ConstantInt>(III->getOperand(2)))
13167 return 0;
13168 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013169
13170 // If this is an insert to the element we are looking for, return the
13171 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000013172 if (EltNo == IIElt)
13173 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013174
13175 // Otherwise, the insertelement doesn't modify the value, recurse on its
13176 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000013177 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000013178 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000013179 unsigned LHSWidth =
13180 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000013181 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000013182 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013183 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013184 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013185 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000013186 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013187 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013188 }
13189
13190 // Otherwise, we don't know.
13191 return 0;
13192}
13193
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013194Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000013195 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000013196 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013197 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013198
Dan Gohman07a96762007-07-16 14:29:03 +000013199 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000013200 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000013201 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013202
Reid Spencer9d6565a2007-02-15 02:26:10 +000013203 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000013204 // If vector val is constant with all elements the same, replace EI with
13205 // that element. When the elements are not identical, we cannot replace yet
13206 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000013207 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013208 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000013209 if (C->getOperand(i) != op0) {
13210 op0 = 0;
13211 break;
13212 }
13213 if (op0)
13214 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013215 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000013216
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013217 // If extracting a specified index from the vector, see if we can recursively
13218 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000013219 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000013220 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013221 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013222
13223 // If this is extracting an invalid index, turn this into undef, to avoid
13224 // crashing the code below.
13225 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013226 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013227
Chris Lattner867b99f2006-10-05 06:55:50 +000013228 // This instruction only demands the single element from the input vector.
13229 // If the input vector has a single use, simplify it based on this use
13230 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013231 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013232 APInt UndefElts(VectorWidth, 0);
13233 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013234 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013235 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013236 EI.setOperand(0, V);
13237 return &EI;
13238 }
13239 }
13240
Owen Andersond672ecb2009-07-03 00:17:18 +000013241 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013242 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013243
13244 // If the this extractelement is directly using a bitcast from a vector of
13245 // the same number of elements, see if we can find the source element from
13246 // it. In this case, we will end up needing to bitcast the scalars.
13247 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13248 if (const VectorType *VT =
13249 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13250 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013251 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13252 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013253 return new BitCastInst(Elt, EI.getType());
13254 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013255 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013256
Chris Lattner73fa49d2006-05-25 22:53:38 +000013257 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013258 // Push extractelement into predecessor operation if legal and
13259 // profitable to do so
13260 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13261 if (I->hasOneUse() &&
13262 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13263 Value *newEI0 =
13264 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13265 EI.getName()+".lhs");
13266 Value *newEI1 =
13267 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13268 EI.getName()+".rhs");
13269 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013270 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013271 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013272 // Extracting the inserted element?
13273 if (IE->getOperand(2) == EI.getOperand(1))
13274 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13275 // If the inserted and extracted elements are constants, they must not
13276 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013277 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013278 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013279 EI.setOperand(0, IE->getOperand(0));
13280 return &EI;
13281 }
13282 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13283 // If this is extracting an element from a shufflevector, figure out where
13284 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013285 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13286 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013287 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013288 unsigned LHSWidth =
13289 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13290
13291 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013292 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013293 else if (SrcIdx < LHSWidth*2) {
13294 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013295 Src = SVI->getOperand(1);
13296 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013297 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013298 }
Eric Christophera3500da2009-07-25 02:28:41 +000013299 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000013300 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13301 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013302 }
13303 }
Eli Friedman2451a642009-07-18 23:06:53 +000013304 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013305 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013306 return 0;
13307}
13308
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013309/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13310/// elements from either LHS or RHS, return the shuffle mask and true.
13311/// Otherwise, return false.
13312static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000013313 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013314 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013315 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13316 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013317 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013318
13319 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013320 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013321 return true;
13322 } else if (V == LHS) {
13323 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013324 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013325 return true;
13326 } else if (V == RHS) {
13327 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013328 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013329 return true;
13330 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13331 // If this is an insert of an extract from some other vector, include it.
13332 Value *VecOp = IEI->getOperand(0);
13333 Value *ScalarOp = IEI->getOperand(1);
13334 Value *IdxOp = IEI->getOperand(2);
13335
Chris Lattnerd929f062006-04-27 21:14:21 +000013336 if (!isa<ConstantInt>(IdxOp))
13337 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013338 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013339
13340 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13341 // Okay, we can handle this if the vector we are insertinting into is
13342 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013343 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013344 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013345 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013346 return true;
13347 }
13348 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13349 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013350 EI->getOperand(0)->getType() == V->getType()) {
13351 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013352 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013353
13354 // This must be extracting from either LHS or RHS.
13355 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13356 // Okay, we can handle this if the vector we are insertinting into is
13357 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013358 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013359 // If so, update the mask to reflect the inserted value.
13360 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013361 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013362 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013363 } else {
13364 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013365 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013366 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013367
13368 }
13369 return true;
13370 }
13371 }
13372 }
13373 }
13374 }
13375 // TODO: Handle shufflevector here!
13376
13377 return false;
13378}
13379
13380/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13381/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13382/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013383static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013384 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013385 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013386 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013387 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013388 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013389
13390 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013391 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013392 return V;
13393 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013394 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013395 return V;
13396 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13397 // If this is an insert of an extract from some other vector, include it.
13398 Value *VecOp = IEI->getOperand(0);
13399 Value *ScalarOp = IEI->getOperand(1);
13400 Value *IdxOp = IEI->getOperand(2);
13401
13402 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13403 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13404 EI->getOperand(0)->getType() == V->getType()) {
13405 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013406 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13407 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013408
13409 // Either the extracted from or inserted into vector must be RHSVec,
13410 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013411 if (EI->getOperand(0) == RHS || RHS == 0) {
13412 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013413 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013414 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013415 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013416 return V;
13417 }
13418
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013419 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013420 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13421 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013422 // Everything but the extracted element is replaced with the RHS.
13423 for (unsigned i = 0; i != NumElts; ++i) {
13424 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013425 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013426 }
13427 return V;
13428 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013429
13430 // If this insertelement is a chain that comes from exactly these two
13431 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013432 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13433 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013434 return EI->getOperand(0);
13435
Chris Lattnerefb47352006-04-15 01:39:45 +000013436 }
13437 }
13438 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013439 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013440
13441 // Otherwise, can't do anything fancy. Return an identity vector.
13442 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013443 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013444 return V;
13445}
13446
13447Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13448 Value *VecOp = IE.getOperand(0);
13449 Value *ScalarOp = IE.getOperand(1);
13450 Value *IdxOp = IE.getOperand(2);
13451
Chris Lattner599ded12007-04-09 01:11:16 +000013452 // Inserting an undef or into an undefined place, remove this.
13453 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13454 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013455
Chris Lattnerefb47352006-04-15 01:39:45 +000013456 // If the inserted element was extracted from some other vector, and if the
13457 // indexes are constant, try to turn this into a shufflevector operation.
13458 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13459 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13460 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013461 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013462 unsigned ExtractedIdx =
13463 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013464 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013465
13466 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13467 return ReplaceInstUsesWith(IE, VecOp);
13468
13469 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013470 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013471
13472 // If we are extracting a value from a vector, then inserting it right
13473 // back into the same place, just use the input vector.
13474 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13475 return ReplaceInstUsesWith(IE, VecOp);
13476
Chris Lattnerefb47352006-04-15 01:39:45 +000013477 // If this insertelement isn't used by some other insertelement, turn it
13478 // (and any insertelements it points to), into one big shuffle.
13479 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13480 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013481 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013482 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013483 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013484 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013485 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013486 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013487 }
13488 }
13489 }
13490
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013491 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13492 APInt UndefElts(VWidth, 0);
13493 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13494 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13495 return &IE;
13496
Chris Lattnerefb47352006-04-15 01:39:45 +000013497 return 0;
13498}
13499
13500
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013501Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13502 Value *LHS = SVI.getOperand(0);
13503 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013504 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013505
13506 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013507
Chris Lattner867b99f2006-10-05 06:55:50 +000013508 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013509 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013510 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013511
Dan Gohman488fbfc2008-09-09 18:11:14 +000013512 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013513
13514 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13515 return 0;
13516
Evan Cheng388df622009-02-03 10:05:09 +000013517 APInt UndefElts(VWidth, 0);
13518 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13519 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013520 LHS = SVI.getOperand(0);
13521 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013522 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013523 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013524
Chris Lattner863bcff2006-05-25 23:48:38 +000013525 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13526 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13527 if (LHS == RHS || isa<UndefValue>(LHS)) {
13528 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013529 // shuffle(undef,undef,mask) -> undef.
13530 return ReplaceInstUsesWith(SVI, LHS);
13531 }
13532
Chris Lattner863bcff2006-05-25 23:48:38 +000013533 // Remap any references to RHS to use LHS.
13534 std::vector<Constant*> Elts;
13535 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013536 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013537 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013538 else {
13539 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013540 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013541 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013542 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013543 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013544 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013545 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013546 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013547 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013548 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013549 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013550 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013551 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013552 LHS = SVI.getOperand(0);
13553 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013554 MadeChange = true;
13555 }
13556
Chris Lattner7b2e27922006-05-26 00:29:06 +000013557 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013558 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013559
Chris Lattner863bcff2006-05-25 23:48:38 +000013560 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13561 if (Mask[i] >= e*2) continue; // Ignore undef values.
13562 // Is this an identity shuffle of the LHS value?
13563 isLHSID &= (Mask[i] == i);
13564
13565 // Is this an identity shuffle of the RHS value?
13566 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013567 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013568
Chris Lattner863bcff2006-05-25 23:48:38 +000013569 // Eliminate identity shuffles.
13570 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13571 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013572
Chris Lattner7b2e27922006-05-26 00:29:06 +000013573 // If the LHS is a shufflevector itself, see if we can combine it with this
13574 // one without producing an unusual shuffle. Here we are really conservative:
13575 // we are absolutely afraid of producing a shuffle mask not in the input
13576 // program, because the code gen may not be smart enough to turn a merged
13577 // shuffle into two specific shuffles: it may produce worse code. As such,
13578 // we only merge two shuffles if the result is one of the two input shuffle
13579 // masks. In this case, merging the shuffles just removes one instruction,
13580 // which we know is safe. This is good for things like turning:
13581 // (splat(splat)) -> splat.
13582 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13583 if (isa<UndefValue>(RHS)) {
13584 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13585
David Greenef941d292009-11-16 21:52:23 +000013586 if (LHSMask.size() == Mask.size()) {
13587 std::vector<unsigned> NewMask;
13588 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013589 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013590 NewMask.push_back(2*e);
13591 else
13592 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013593
David Greenef941d292009-11-16 21:52:23 +000013594 // If the result mask is equal to the src shuffle or this
13595 // shuffle mask, do the replacement.
13596 if (NewMask == LHSMask || NewMask == Mask) {
13597 unsigned LHSInNElts =
13598 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13599 getNumElements();
13600 std::vector<Constant*> Elts;
13601 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13602 if (NewMask[i] >= LHSInNElts*2) {
13603 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13604 } else {
13605 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13606 NewMask[i]));
13607 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013608 }
David Greenef941d292009-11-16 21:52:23 +000013609 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13610 LHSSVI->getOperand(1),
13611 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013612 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013613 }
13614 }
13615 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013616
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013617 return MadeChange ? &SVI : 0;
13618}
13619
13620
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013621
Chris Lattnerea1c4542004-12-08 23:43:58 +000013622
13623/// TryToSinkInstruction - Try to move the specified instruction from its
13624/// current block into the beginning of DestBlock, which can only happen if it's
13625/// safe to move the instruction past all of the instructions between it and the
13626/// end of its block.
13627static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13628 assert(I->hasOneUse() && "Invariants didn't hold!");
13629
Chris Lattner108e9022005-10-27 17:13:11 +000013630 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013631 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013632 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013633
Chris Lattnerea1c4542004-12-08 23:43:58 +000013634 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013635 if (isa<AllocaInst>(I) && I->getParent() ==
13636 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013637 return false;
13638
Chris Lattner96a52a62004-12-09 07:14:34 +000013639 // We can only sink load instructions if there is nothing between the load and
13640 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013641 if (I->mayReadFromMemory()) {
13642 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013643 Scan != E; ++Scan)
13644 if (Scan->mayWriteToMemory())
13645 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013646 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013647
Dan Gohman02dea8b2008-05-23 21:05:58 +000013648 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013649
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013650 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013651 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013652 ++NumSunkInst;
13653 return true;
13654}
13655
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013656
13657/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13658/// all reachable code to the worklist.
13659///
13660/// This has a couple of tricks to make the code faster and more powerful. In
13661/// particular, we constant fold and DCE instructions as we go, to avoid adding
13662/// them to the worklist (this significantly speeds up instcombine on code where
13663/// many instructions are dead or constant). Additionally, if we find a branch
13664/// whose condition is a known constant, we only visit the reachable successors.
13665///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013666static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013667 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013668 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013669 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013670 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013671 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013672 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013673
13674 std::vector<Instruction*> InstrsForInstCombineWorklist;
13675 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013676
Chris Lattner2ee743b2009-10-15 04:59:28 +000013677 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13678
Chris Lattner2c7718a2007-03-23 19:17:18 +000013679 while (!Worklist.empty()) {
13680 BB = Worklist.back();
13681 Worklist.pop_back();
13682
13683 // We have now visited this block! If we've already been here, ignore it.
13684 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013685
Chris Lattner2c7718a2007-03-23 19:17:18 +000013686 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13687 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013688
Chris Lattner2c7718a2007-03-23 19:17:18 +000013689 // DCE instruction if trivially dead.
13690 if (isInstructionTriviallyDead(Inst)) {
13691 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013692 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013693 Inst->eraseFromParent();
13694 continue;
13695 }
13696
13697 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013698 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013699 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013700 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13701 << *Inst << '\n');
13702 Inst->replaceAllUsesWith(C);
13703 ++NumConstProp;
13704 Inst->eraseFromParent();
13705 continue;
13706 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013707
13708
13709
13710 if (TD) {
13711 // See if we can constant fold its operands.
13712 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13713 i != e; ++i) {
13714 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13715 if (CE == 0) continue;
13716
13717 // If we already folded this constant, don't try again.
13718 if (!FoldedConstants.insert(CE))
13719 continue;
13720
Chris Lattner7b550cc2009-11-06 04:27:31 +000013721 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013722 if (NewC && NewC != CE) {
13723 *i = NewC;
13724 MadeIRChange = true;
13725 }
13726 }
13727 }
13728
Devang Patel7fe1dec2008-11-19 18:56:50 +000013729
Chris Lattner67f7d542009-10-12 03:58:40 +000013730 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013731 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013732
13733 // Recursively visit successors. If this is a branch or switch on a
13734 // constant, only visit the reachable successor.
13735 TerminatorInst *TI = BB->getTerminator();
13736 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13737 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13738 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013739 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013740 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013741 continue;
13742 }
13743 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13744 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13745 // See if this is an explicit destination.
13746 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13747 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013748 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013749 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013750 continue;
13751 }
13752
13753 // Otherwise it is the default destination.
13754 Worklist.push_back(SI->getSuccessor(0));
13755 continue;
13756 }
13757 }
13758
13759 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13760 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013761 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013762
13763 // Once we've found all of the instructions to add to instcombine's worklist,
13764 // add them in reverse order. This way instcombine will visit from the top
13765 // of the function down. This jives well with the way that it adds all uses
13766 // of instructions to the worklist after doing a transformation, thus avoiding
13767 // some N^2 behavior in pathological cases.
13768 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13769 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013770
13771 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013772}
13773
Chris Lattnerec9c3582007-03-03 02:04:50 +000013774bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013775 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013776
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013777 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13778 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013779
Chris Lattnerb3d59702005-07-07 20:40:38 +000013780 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013781 // Do a depth-first traversal of the function, populate the worklist with
13782 // the reachable instructions. Ignore blocks that are not reachable. Keep
13783 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013784 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013785 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013786
Chris Lattnerb3d59702005-07-07 20:40:38 +000013787 // Do a quick scan over the function. If we find any blocks that are
13788 // unreachable, remove any instructions inside of them. This prevents
13789 // the instcombine code from having to deal with some bad special cases.
13790 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13791 if (!Visited.count(BB)) {
13792 Instruction *Term = BB->getTerminator();
13793 while (Term != BB->begin()) { // Remove instrs bottom-up
13794 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013795
Chris Lattnerbdff5482009-08-23 04:37:46 +000013796 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013797 // A debug intrinsic shouldn't force another iteration if we weren't
13798 // going to do one without it.
13799 if (!isa<DbgInfoIntrinsic>(I)) {
13800 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013801 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013802 }
Devang Patel228ebd02009-10-13 22:56:32 +000013803
Devang Patel228ebd02009-10-13 22:56:32 +000013804 // If I is not void type then replaceAllUsesWith undef.
13805 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013806 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013807 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013808 I->eraseFromParent();
13809 }
13810 }
13811 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013812
Chris Lattner873ff012009-08-30 05:55:36 +000013813 while (!Worklist.isEmpty()) {
13814 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013815 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013816
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013817 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013818 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013819 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013820 EraseInstFromFunction(*I);
13821 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013822 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013823 continue;
13824 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013825
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013826 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013827 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013828 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013829 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013830
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013831 // Add operands to the worklist.
13832 ReplaceInstUsesWith(*I, C);
13833 ++NumConstProp;
13834 EraseInstFromFunction(*I);
13835 MadeIRChange = true;
13836 continue;
13837 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013838
Chris Lattnerea1c4542004-12-08 23:43:58 +000013839 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013840 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013841 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013842 Instruction *UserInst = cast<Instruction>(I->use_back());
13843 BasicBlock *UserParent;
13844
13845 // Get the block the use occurs in.
13846 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13847 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13848 else
13849 UserParent = UserInst->getParent();
13850
Chris Lattnerea1c4542004-12-08 23:43:58 +000013851 if (UserParent != BB) {
13852 bool UserIsSuccessor = false;
13853 // See if the user is one of our successors.
13854 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13855 if (*SI == UserParent) {
13856 UserIsSuccessor = true;
13857 break;
13858 }
13859
13860 // If the user is one of our immediate successors, and if that successor
13861 // only has us as a predecessors (we'd have to split the critical edge
13862 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013863 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013864 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013865 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013866 }
13867 }
13868
Chris Lattner74381062009-08-30 07:44:24 +000013869 // Now that we have an instruction, try combining it to simplify it.
13870 Builder->SetInsertPoint(I->getParent(), I);
13871
Reid Spencera9b81012007-03-26 17:44:01 +000013872#ifndef NDEBUG
13873 std::string OrigI;
13874#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013875 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013876 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13877
Chris Lattner90ac28c2002-08-02 19:29:35 +000013878 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013879 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013880 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013881 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013882 DEBUG(errs() << "IC: Old = " << *I << '\n'
13883 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013884
Chris Lattnerf523d062004-06-09 05:08:07 +000013885 // Everything uses the new instruction now.
13886 I->replaceAllUsesWith(Result);
13887
13888 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013889 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013890 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013891
Chris Lattner6934a042007-02-11 01:23:03 +000013892 // Move the name to the new instruction first.
13893 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013894
13895 // Insert the new instruction into the basic block...
13896 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013897 BasicBlock::iterator InsertPos = I;
13898
13899 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13900 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13901 ++InsertPos;
13902
13903 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013904
Chris Lattner7a1e9242009-08-30 06:13:40 +000013905 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013906 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013907#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013908 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13909 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013910#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013911
Chris Lattner90ac28c2002-08-02 19:29:35 +000013912 // If the instruction was modified, it's possible that it is now dead.
13913 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013914 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013915 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013916 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013917 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013918 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013919 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013920 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013921 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013922 }
13923 }
13924
Chris Lattner873ff012009-08-30 05:55:36 +000013925 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013926 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013927}
13928
Chris Lattnerec9c3582007-03-03 02:04:50 +000013929
13930bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013931 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013932 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013933 TD = getAnalysisIfAvailable<TargetData>();
13934
Chris Lattner74381062009-08-30 07:44:24 +000013935
13936 /// Builder - This is an IRBuilder that automatically inserts new
13937 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013938 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013939 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013940 InstCombineIRInserter(Worklist));
13941 Builder = &TheBuilder;
13942
Chris Lattnerec9c3582007-03-03 02:04:50 +000013943 bool EverMadeChange = false;
13944
13945 // Iterate while there is work to do.
13946 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013947 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013948 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013949
13950 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013951 return EverMadeChange;
13952}
13953
Brian Gaeke96d4bf72004-07-27 17:43:21 +000013954FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013955 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013956}