blob: 23db4bb0587555b7fd33e336d875e8c7c16159ad [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,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +0000262 GlobalVariable *GV, CmpInst &ICI,
263 ConstantInt *AndCst = 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000264 Instruction *visitFCmpInst(FCmpInst &I);
265 Instruction *visitICmpInst(ICmpInst &I);
266 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000267 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
268 Instruction *LHS,
269 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000270 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
271 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000272 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000273 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000274 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000275 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000276 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000277 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000278 Instruction *commonCastTransforms(CastInst &CI);
279 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000280 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000281 Instruction *visitTrunc(TruncInst &CI);
282 Instruction *visitZExt(ZExtInst &CI);
283 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000284 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000285 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000286 Instruction *visitFPToUI(FPToUIInst &FI);
287 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000288 Instruction *visitUIToFP(CastInst &CI);
289 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000290 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000291 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000292 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000293 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
294 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000295 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000296 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
297 Value *A, Value *B, Instruction &Outer,
298 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000299 Instruction *visitSelectInst(SelectInst &SI);
300 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000301 Instruction *visitCallInst(CallInst &CI);
302 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000303
304 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000305 Instruction *visitPHINode(PHINode &PN);
306 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000307 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000308 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000309 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000310 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000311 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000312 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000313 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000314 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000315 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000316 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000317
318 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000319 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000320
Chris Lattner9fe38862003-06-19 17:00:31 +0000321 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000322 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000323 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000324 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000325 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
326 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000327 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000328 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
329
Chris Lattner9fe38862003-06-19 17:00:31 +0000330
Chris Lattner28977af2004-04-05 01:30:19 +0000331 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000332 // InsertNewInstBefore - insert an instruction New before instruction Old
333 // in the program. Add the new instruction to the worklist.
334 //
Chris Lattner955f3312004-09-28 21:48:02 +0000335 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000336 assert(New && New->getParent() == 0 &&
337 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000338 BasicBlock *BB = Old.getParent();
339 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000340 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000341 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000342 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000343
Chris Lattner8b170942002-08-09 23:47:40 +0000344 // ReplaceInstUsesWith - This method is to be used when an instruction is
345 // found to be dead, replacable with another preexisting expression. Here
346 // we add all uses of I to the worklist, replace all uses of I with the new
347 // value, then return I, so that the inst combiner will know that I was
348 // modified.
349 //
350 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000351 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000352
353 // If we are replacing the instruction with itself, this must be in a
354 // segment of unreachable code, so just clobber the instruction.
355 if (&I == V)
356 V = UndefValue::get(I.getType());
357
358 I.replaceAllUsesWith(V);
359 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000360 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000361
362 // EraseInstFromFunction - When dealing with an instruction that has side
363 // effects or produces a void value, we can't rely on DCE to delete the
364 // instruction. Instead, visit methods should return the value returned by
365 // this function.
366 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000367 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000368
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000369 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000370 // Make sure that we reprocess all operands now that we reduced their
371 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000372 if (I.getNumOperands() < 8) {
373 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
374 if (Instruction *Op = dyn_cast<Instruction>(*i))
375 Worklist.Add(Op);
376 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000377 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000378 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000379 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000380 return 0; // Don't do anything with FI
381 }
Chris Lattner173234a2008-06-02 01:18:21 +0000382
383 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
384 APInt &KnownOne, unsigned Depth = 0) const {
385 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
386 }
387
388 bool MaskedValueIsZero(Value *V, const APInt &Mask,
389 unsigned Depth = 0) const {
390 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
391 }
392 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
393 return llvm::ComputeNumSignBits(Op, TD, Depth);
394 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000395
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000396 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000397
Reid Spencere4d87aa2006-12-23 06:05:41 +0000398 /// SimplifyCommutative - This performs a few simplifications for
399 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000400 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000401
Chris Lattner886ab6c2009-01-31 08:15:18 +0000402 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
403 /// based on the demanded bits.
404 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
405 APInt& KnownZero, APInt& KnownOne,
406 unsigned Depth);
407 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000408 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000409 unsigned Depth=0);
410
411 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
412 /// SimplifyDemandedBits knows about. See if the instruction has any
413 /// properties that allow us to simplify its operands.
414 bool SimplifyDemandedInstructionBits(Instruction &Inst);
415
Evan Cheng388df622009-02-03 10:05:09 +0000416 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
417 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000418
Chris Lattner5d1704d2009-09-27 19:57:57 +0000419 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
420 // which has a PHI node as operand #0, see if we can fold the instruction
421 // into the PHI (which is only possible if all operands to the PHI are
422 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000423 //
424 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
425 // that would normally be unprofitable because they strongly encourage jump
426 // threading.
427 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000428
Chris Lattnerbac32862004-11-14 19:13:23 +0000429 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
430 // operator and they all are only used by the PHI, PHI together their
431 // inputs, and do the operation once, to the result of the PHI.
432 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000433 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000434 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000435 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000436
Chris Lattner7da52b22006-11-01 04:51:18 +0000437
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000438 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
439 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000440
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000441 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000442 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000443 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000444 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000445 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000446 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000447 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000448 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000449 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000450
Chris Lattnerafe91a52006-06-15 19:07:26 +0000451
Reid Spencerc55b2432006-12-13 18:21:21 +0000452 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000453
Dan Gohman6de29f82009-06-15 22:12:54 +0000454 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000455 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000456 unsigned GetOrEnforceKnownAlignment(Value *V,
457 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000458
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000459 };
Chris Lattner873ff012009-08-30 05:55:36 +0000460} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000461
Dan Gohman844731a2008-05-13 00:00:25 +0000462char InstCombiner::ID = 0;
463static RegisterPass<InstCombiner>
464X("instcombine", "Combine redundant instructions");
465
Chris Lattner4f98c562003-03-10 21:43:22 +0000466// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000467// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000468static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000469 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000470 if (BinaryOperator::isNeg(V) ||
471 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000472 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000473 return 3;
474 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000475 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000476 if (isa<Argument>(V)) return 3;
477 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000478}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000479
Chris Lattnerc8802d22003-03-11 00:12:48 +0000480// isOnlyUse - Return true if this instruction will be deleted if we stop using
481// it.
482static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000483 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000484}
485
Chris Lattner4cb170c2004-02-23 06:38:22 +0000486// getPromotedType - Return the specified type promoted as it would be to pass
487// though a va_arg area...
488static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000489 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
490 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000492 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000493 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000494}
495
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000496/// ShouldChangeType - Return true if it is desirable to convert a computation
497/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
498/// type for example, or from a smaller to a larger illegal type.
499static bool ShouldChangeType(const Type *From, const Type *To,
500 const TargetData *TD) {
501 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
502
503 // If we don't have TD, we don't know if the source/dest are legal.
504 if (!TD) return false;
505
506 unsigned FromWidth = From->getPrimitiveSizeInBits();
507 unsigned ToWidth = To->getPrimitiveSizeInBits();
508 bool FromLegal = TD->isLegalInteger(FromWidth);
509 bool ToLegal = TD->isLegalInteger(ToWidth);
510
511 // If this is a legal integer from type, and the result would be an illegal
512 // type, don't do the transformation.
513 if (FromLegal && !ToLegal)
514 return false;
515
516 // Otherwise, if both are illegal, do not increase the size of the result. We
517 // do allow things like i160 -> i64, but not i64 -> i160.
518 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
519 return false;
520
521 return true;
522}
523
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000524/// getBitCastOperand - If the specified operand is a CastInst, a constant
525/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
526/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000527static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000528 if (Operator *O = dyn_cast<Operator>(V)) {
529 if (O->getOpcode() == Instruction::BitCast)
530 return O->getOperand(0);
531 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
532 if (GEP->hasAllZeroIndices())
533 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000534 }
Chris Lattnereed48272005-09-13 00:40:14 +0000535 return 0;
536}
537
Reid Spencer3da59db2006-11-27 01:05:10 +0000538/// This function is a wrapper around CastInst::isEliminableCastPair. It
539/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000540static Instruction::CastOps
541isEliminableCastPair(
542 const CastInst *CI, ///< The first cast instruction
543 unsigned opcode, ///< The opcode of the second cast instruction
544 const Type *DstTy, ///< The target type for the second cast instruction
545 TargetData *TD ///< The target data for pointer size
546) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000547
Reid Spencer3da59db2006-11-27 01:05:10 +0000548 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
549 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000550
Reid Spencer3da59db2006-11-27 01:05:10 +0000551 // Get the opcodes of the two Cast instructions
552 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
553 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000554
Chris Lattnera0e69692009-03-24 18:35:40 +0000555 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000556 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000557 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000558
559 // We don't want to form an inttoptr or ptrtoint that converts to an integer
560 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000561 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000562 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000563 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000564 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000565 Res = 0;
566
567 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000568}
569
570/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
571/// in any code being generated. It does not require codegen if V is simple
572/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000573static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
574 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000575 if (V->getType() == Ty || isa<Constant>(V)) return false;
576
Chris Lattner01575b72006-05-25 23:24:33 +0000577 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000578 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000579 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000580 return false;
581 return true;
582}
583
Chris Lattner4f98c562003-03-10 21:43:22 +0000584// SimplifyCommutative - This performs a few simplifications for commutative
585// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000586//
Chris Lattner4f98c562003-03-10 21:43:22 +0000587// 1. Order operands such that they are listed from right (least complex) to
588// left (most complex). This puts constants before unary operators before
589// binary operators.
590//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000591// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
592// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000593//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000594bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000595 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000596 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000597 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000598
Chris Lattner4f98c562003-03-10 21:43:22 +0000599 if (!I.isAssociative()) return Changed;
600 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000601 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
602 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
603 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000605 cast<Constant>(I.getOperand(1)),
606 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000607 I.setOperand(0, Op->getOperand(0));
608 I.setOperand(1, Folded);
609 return true;
610 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
611 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
612 isOnlyUse(Op) && isOnlyUse(Op1)) {
613 Constant *C1 = cast<Constant>(Op->getOperand(1));
614 Constant *C2 = cast<Constant>(Op1->getOperand(1));
615
616 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000617 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000618 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000619 Op1->getOperand(0),
620 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000621 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622 I.setOperand(0, New);
623 I.setOperand(1, Folded);
624 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000625 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000626 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000627 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000628}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000629
Chris Lattner8d969642003-03-10 23:06:50 +0000630// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
631// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000632//
Dan Gohman186a6362009-08-12 16:04:34 +0000633static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000634 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000635 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000636
Chris Lattner0ce85802004-12-14 20:08:06 +0000637 // Constants can be considered to be negated values if they can be folded.
638 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000639 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000640
641 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
642 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000643 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000644
Chris Lattner8d969642003-03-10 23:06:50 +0000645 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000646}
647
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000648// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
649// instruction if the LHS is a constant negative zero (which is the 'negate'
650// form).
651//
Dan Gohman186a6362009-08-12 16:04:34 +0000652static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000653 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000654 return BinaryOperator::getFNegArgument(V);
655
656 // Constants can be considered to be negated values if they can be folded.
657 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000658 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000659
660 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
661 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000662 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000663
664 return 0;
665}
666
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000667/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
668/// returning the kind and providing the out parameter results if we
669/// successfully match.
670static SelectPatternFlavor
671MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
672 SelectInst *SI = dyn_cast<SelectInst>(V);
673 if (SI == 0) return SPF_UNKNOWN;
674
675 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
676 if (ICI == 0) return SPF_UNKNOWN;
677
678 LHS = ICI->getOperand(0);
679 RHS = ICI->getOperand(1);
680
681 // (icmp X, Y) ? X : Y
682 if (SI->getTrueValue() == ICI->getOperand(0) &&
683 SI->getFalseValue() == ICI->getOperand(1)) {
684 switch (ICI->getPredicate()) {
685 default: return SPF_UNKNOWN; // Equality.
686 case ICmpInst::ICMP_UGT:
687 case ICmpInst::ICMP_UGE: return SPF_UMAX;
688 case ICmpInst::ICMP_SGT:
689 case ICmpInst::ICMP_SGE: return SPF_SMAX;
690 case ICmpInst::ICMP_ULT:
691 case ICmpInst::ICMP_ULE: return SPF_UMIN;
692 case ICmpInst::ICMP_SLT:
693 case ICmpInst::ICMP_SLE: return SPF_SMIN;
694 }
695 }
696
697 // (icmp X, Y) ? Y : X
698 if (SI->getTrueValue() == ICI->getOperand(1) &&
699 SI->getFalseValue() == ICI->getOperand(0)) {
700 switch (ICI->getPredicate()) {
701 default: return SPF_UNKNOWN; // Equality.
702 case ICmpInst::ICMP_UGT:
703 case ICmpInst::ICMP_UGE: return SPF_UMIN;
704 case ICmpInst::ICMP_SGT:
705 case ICmpInst::ICMP_SGE: return SPF_SMIN;
706 case ICmpInst::ICMP_ULT:
707 case ICmpInst::ICMP_ULE: return SPF_UMAX;
708 case ICmpInst::ICMP_SLT:
709 case ICmpInst::ICMP_SLE: return SPF_SMAX;
710 }
711 }
712
713 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
714
715 return SPF_UNKNOWN;
716}
717
Chris Lattner48b59ec2009-10-26 15:40:07 +0000718/// isFreeToInvert - Return true if the specified value is free to invert (apply
719/// ~ to). This happens in cases where the ~ can be eliminated.
720static inline bool isFreeToInvert(Value *V) {
721 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000722 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000723 return true;
724
725 // Constants can be considered to be not'ed values.
726 if (isa<ConstantInt>(V))
727 return true;
728
729 // Compares can be inverted if they have a single use.
730 if (CmpInst *CI = dyn_cast<CmpInst>(V))
731 return CI->hasOneUse();
732
733 return false;
734}
735
736static inline Value *dyn_castNotVal(Value *V) {
737 // If this is not(not(x)) don't return that this is a not: we want the two
738 // not's to be folded first.
739 if (BinaryOperator::isNot(V)) {
740 Value *Operand = BinaryOperator::getNotArgument(V);
741 if (!isFreeToInvert(Operand))
742 return Operand;
743 }
Chris Lattner8d969642003-03-10 23:06:50 +0000744
745 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000746 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000747 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000748 return 0;
749}
750
Chris Lattner48b59ec2009-10-26 15:40:07 +0000751
752
Chris Lattnerc8802d22003-03-11 00:12:48 +0000753// dyn_castFoldableMul - If this value is a multiply that can be folded into
754// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000755// non-constant operand of the multiply, and set CST to point to the multiplier.
756// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000757//
Dan Gohman186a6362009-08-12 16:04:34 +0000758static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000759 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000760 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000761 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000762 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000763 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000764 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000765 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000766 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000767 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000768 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000769 CST = ConstantInt::get(V->getType()->getContext(),
770 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000771 return I->getOperand(0);
772 }
773 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000774 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000775}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000776
Reid Spencer7177c3a2007-03-25 05:33:51 +0000777/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000778static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000779 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000780 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000781}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000782/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000783static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000784 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000785 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000786}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000787/// MultiplyOverflows - True if the multiply can not be expressed in an int
788/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000789static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000790 uint32_t W = C1->getBitWidth();
791 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
792 if (sign) {
793 LHSExt.sext(W * 2);
794 RHSExt.sext(W * 2);
795 } else {
796 LHSExt.zext(W * 2);
797 RHSExt.zext(W * 2);
798 }
799
800 APInt MulExt = LHSExt * RHSExt;
801
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000802 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000803 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000804
805 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
806 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
807 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000808}
Chris Lattner955f3312004-09-28 21:48:02 +0000809
Reid Spencere7816b52007-03-08 01:52:58 +0000810
Chris Lattner255d8912006-02-11 09:31:47 +0000811/// ShrinkDemandedConstant - Check to see if the specified operand of the
812/// specified instruction is a constant integer. If so, check to see if there
813/// are any bits set in the constant that are not demanded. If so, shrink the
814/// constant and return true.
815static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000816 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000817 assert(I && "No instruction?");
818 assert(OpNo < I->getNumOperands() && "Operand index too large");
819
820 // If the operand is not a constant integer, nothing to do.
821 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
822 if (!OpC) return false;
823
824 // If there are no bits set that aren't demanded, nothing to do.
825 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
826 if ((~Demanded & OpC->getValue()) == 0)
827 return false;
828
829 // This instruction is producing bits that are not demanded. Shrink the RHS.
830 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000831 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000832 return true;
833}
834
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000835// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
836// set of known zero and one bits, compute the maximum and minimum values that
837// could have the specified known zero and known one bits, returning them in
838// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000839static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000840 const APInt& KnownOne,
841 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000842 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
843 KnownZero.getBitWidth() == Min.getBitWidth() &&
844 KnownZero.getBitWidth() == Max.getBitWidth() &&
845 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000846 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000847
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000848 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
849 // bit if it is unknown.
850 Min = KnownOne;
851 Max = KnownOne|UnknownBits;
852
Dan Gohman1c8491e2009-04-25 17:12:48 +0000853 if (UnknownBits.isNegative()) { // Sign bit is unknown
854 Min.set(Min.getBitWidth()-1);
855 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000856 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000857}
858
859// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
860// a set of known zero and one bits, compute the maximum and minimum values that
861// could have the specified known zero and known one bits, returning them in
862// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000863static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000864 const APInt &KnownOne,
865 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000866 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
867 KnownZero.getBitWidth() == Min.getBitWidth() &&
868 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000869 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000870 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000871
872 // The minimum value is when the unknown bits are all zeros.
873 Min = KnownOne;
874 // The maximum value is when the unknown bits are all ones.
875 Max = KnownOne|UnknownBits;
876}
Chris Lattner255d8912006-02-11 09:31:47 +0000877
Chris Lattner886ab6c2009-01-31 08:15:18 +0000878/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
879/// SimplifyDemandedBits knows about. See if the instruction has any
880/// properties that allow us to simplify its operands.
881bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000882 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000883 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
884 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
885
886 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
887 KnownZero, KnownOne, 0);
888 if (V == 0) return false;
889 if (V == &Inst) return true;
890 ReplaceInstUsesWith(Inst, V);
891 return true;
892}
893
894/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
895/// specified instruction operand if possible, updating it in place. It returns
896/// true if it made any change and false otherwise.
897bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
898 APInt &KnownZero, APInt &KnownOne,
899 unsigned Depth) {
900 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
901 KnownZero, KnownOne, Depth);
902 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000903 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000904 return true;
905}
906
907
908/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
909/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000910/// that only the bits set in DemandedMask of the result of V are ever used
911/// downstream. Consequently, depending on the mask and V, it may be possible
912/// to replace V with a constant or one of its operands. In such cases, this
913/// function does the replacement and returns true. In all other cases, it
914/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000915/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000916/// to be zero in the expression. These are provided to potentially allow the
917/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
918/// the expression. KnownOne and KnownZero always follow the invariant that
919/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
920/// the bits in KnownOne and KnownZero may only be accurate for those bits set
921/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
922/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000923///
924/// This returns null if it did not change anything and it permits no
925/// simplification. This returns V itself if it did some simplification of V's
926/// operands based on the information about what bits are demanded. This returns
927/// some other non-null value if it found out that V is equal to another value
928/// in the context where the specified bits are demanded, but not for all users.
929Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
930 APInt &KnownZero, APInt &KnownOne,
931 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000932 assert(V != 0 && "Null pointer of Value???");
933 assert(Depth <= 6 && "Limit Search Depth");
934 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000935 const Type *VTy = V->getType();
936 assert((TD || !isa<PointerType>(VTy)) &&
937 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000938 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
939 (!VTy->isIntOrIntVector() ||
940 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000941 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000943 "Value *V, DemandedMask, KnownZero and KnownOne "
944 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000945 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
946 // We know all of the bits for a constant!
947 KnownOne = CI->getValue() & DemandedMask;
948 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000949 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000950 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000951 if (isa<ConstantPointerNull>(V)) {
952 // We know all of the bits for a constant!
953 KnownOne.clear();
954 KnownZero = DemandedMask;
955 return 0;
956 }
957
Chris Lattner08d2cc72009-01-31 07:26:06 +0000958 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000959 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000960 if (DemandedMask == 0) { // Not demanding any bits from V.
961 if (isa<UndefValue>(V))
962 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000963 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 }
965
Chris Lattner4598c942009-01-31 08:24:16 +0000966 if (Depth == 6) // Limit search depth.
967 return 0;
968
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000969 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
970 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
971
Dan Gohman1c8491e2009-04-25 17:12:48 +0000972 Instruction *I = dyn_cast<Instruction>(V);
973 if (!I) {
974 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
975 return 0; // Only analyze instructions.
976 }
977
Chris Lattner4598c942009-01-31 08:24:16 +0000978 // If there are multiple uses of this value and we aren't at the root, then
979 // we can't do any simplifications of the operands, because DemandedMask
980 // only reflects the bits demanded by *one* of the users.
981 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000982 // Despite the fact that we can't simplify this instruction in all User's
983 // context, we can at least compute the knownzero/knownone bits, and we can
984 // do simplifications that apply to *just* the one user if we know that
985 // this instruction has a simpler value in that context.
986 if (I->getOpcode() == Instruction::And) {
987 // If either the LHS or the RHS are Zero, the result is zero.
988 ComputeMaskedBits(I->getOperand(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1);
990 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
991 LHSKnownZero, LHSKnownOne, Depth+1);
992
993 // If all of the demanded bits are known 1 on one side, return the other.
994 // These bits cannot contribute to the result of the 'and' in this
995 // context.
996 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
997 (DemandedMask & ~LHSKnownZero))
998 return I->getOperand(0);
999 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1000 (DemandedMask & ~RHSKnownZero))
1001 return I->getOperand(1);
1002
1003 // If all of the demanded bits in the inputs are known zeros, return zero.
1004 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001005 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +00001006
1007 } else if (I->getOpcode() == Instruction::Or) {
1008 // We can simplify (X|Y) -> X or Y in the user's context if we know that
1009 // only bits from X or Y are demanded.
1010
1011 // If either the LHS or the RHS are One, the result is One.
1012 ComputeMaskedBits(I->getOperand(1), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1);
1014 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1015 LHSKnownZero, LHSKnownOne, Depth+1);
1016
1017 // If all of the demanded bits are known zero on one side, return the
1018 // other. These bits cannot contribute to the result of the 'or' in this
1019 // context.
1020 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1021 (DemandedMask & ~LHSKnownOne))
1022 return I->getOperand(0);
1023 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1024 (DemandedMask & ~RHSKnownOne))
1025 return I->getOperand(1);
1026
1027 // If all of the potentially set bits on one side are known to be set on
1028 // the other side, just use the 'other' side.
1029 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1030 (DemandedMask & (~RHSKnownZero)))
1031 return I->getOperand(0);
1032 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1033 (DemandedMask & (~LHSKnownZero)))
1034 return I->getOperand(1);
1035 }
1036
Chris Lattner4598c942009-01-31 08:24:16 +00001037 // Compute the KnownZero/KnownOne bits to simplify things downstream.
1038 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
1039 return 0;
1040 }
1041
1042 // If this is the root being simplified, allow it to have multiple uses,
1043 // just set the DemandedMask to all bits so that we can try to simplify the
1044 // operands. This allows visitTruncInst (for example) to simplify the
1045 // operand of a trunc without duplicating all the logic below.
1046 if (Depth == 0 && !V->hasOneUse())
1047 DemandedMask = APInt::getAllOnesValue(BitWidth);
1048
Reid Spencer8cb68342007-03-12 17:25:59 +00001049 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +00001050 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001051 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +00001052 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 case Instruction::And:
1054 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1056 RHSKnownZero, RHSKnownOne, Depth+1) ||
1057 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +00001058 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001059 return I;
1060 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1061 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001062
1063 // If all of the demanded bits are known 1 on one side, return the other.
1064 // These bits cannot contribute to the result of the 'and'.
1065 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1066 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001067 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001068 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1069 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001070 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001071
1072 // If all of the demanded bits in the inputs are known zeros, return zero.
1073 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +00001074 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +00001075
1076 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001077 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079
1080 // Output known-1 bits are only known if set in both the LHS & RHS.
1081 RHSKnownOne &= LHSKnownOne;
1082 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1083 RHSKnownZero |= LHSKnownZero;
1084 break;
1085 case Instruction::Or:
1086 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001087 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1088 RHSKnownZero, RHSKnownOne, Depth+1) ||
1089 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001090 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 return I;
1092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1093 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001094
1095 // If all of the demanded bits are known zero on one side, return the other.
1096 // These bits cannot contribute to the result of the 'or'.
1097 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1098 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001099 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001100 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1101 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001103
1104 // If all of the potentially set bits on one side are known to be set on
1105 // the other side, just use the 'other' side.
1106 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1107 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1110 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001112
1113 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001114 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001115 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001116
1117 // Output known-0 bits are only known if clear in both the LHS & RHS.
1118 RHSKnownZero &= LHSKnownZero;
1119 // Output known-1 are known to be set if set in either the LHS | RHS.
1120 RHSKnownOne |= LHSKnownOne;
1121 break;
1122 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1) ||
1125 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001126 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 return I;
1128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1129 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001130
1131 // If all of the demanded bits are known zero on one side, return the other.
1132 // These bits cannot contribute to the result of the 'xor'.
1133 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001136 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
1138 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1139 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1140 (RHSKnownOne & LHSKnownOne);
1141 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1142 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1143 (RHSKnownOne & LHSKnownZero);
1144
1145 // If all of the demanded bits are known to be zero on one side or the
1146 // other, turn this into an *inclusive* or.
1147 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001148 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1149 Instruction *Or =
1150 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1151 I->getName());
1152 return InsertNewInstBefore(Or, *I);
1153 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // If all of the demanded bits on one side are known, and all of the set
1156 // bits on that side are also known to be set on the other side, turn this
1157 // into an AND, as we know the bits will be cleared.
1158 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1159 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1160 // all known
1161 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001162 Constant *AndC = Constant::getIntegerValue(VTy,
1163 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001164 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001165 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001166 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 }
1168 }
1169
1170 // If the RHS is a constant, see if we can simplify it.
1171 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001172 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
Chris Lattnerd0883142009-10-11 22:22:13 +00001175 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1176 // are flipping are known to be set, then the xor is just resetting those
1177 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1178 // simplifying both of them.
1179 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1180 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1181 isa<ConstantInt>(I->getOperand(1)) &&
1182 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1183 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1184 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1185 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1186 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1187
1188 Constant *AndC =
1189 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1190 Instruction *NewAnd =
1191 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1192 InsertNewInstBefore(NewAnd, *I);
1193
1194 Constant *XorC =
1195 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1196 Instruction *NewXor =
1197 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1198 return InsertNewInstBefore(NewXor, *I);
1199 }
1200
1201
Reid Spencer8cb68342007-03-12 17:25:59 +00001202 RHSKnownZero = KnownZeroOut;
1203 RHSKnownOne = KnownOneOut;
1204 break;
1205 }
1206 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001207 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1208 RHSKnownZero, RHSKnownOne, Depth+1) ||
1209 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001210 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001211 return I;
1212 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1213 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001216 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1217 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001218 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001219
1220 // Only known if known in both the LHS and RHS.
1221 RHSKnownOne &= LHSKnownOne;
1222 RHSKnownZero &= LHSKnownZero;
1223 break;
1224 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001225 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 DemandedMask.zext(truncBf);
1227 RHSKnownZero.zext(truncBf);
1228 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001229 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001231 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 DemandedMask.trunc(BitWidth);
1233 RHSKnownZero.trunc(BitWidth);
1234 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001235 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 break;
1237 }
1238 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001239 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001241
1242 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1243 if (const VectorType *SrcVTy =
1244 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1245 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1246 // Don't touch a bitcast between vectors of different element counts.
1247 return false;
1248 } else
1249 // Don't touch a scalar-to-vector bitcast.
1250 return false;
1251 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1252 // Don't touch a vector-to-scalar bitcast.
1253 return false;
1254
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001256 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001257 return I;
1258 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 break;
1260 case Instruction::ZExt: {
1261 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001262 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001263
Zhou Shengd48653a2007-03-29 04:45:55 +00001264 DemandedMask.trunc(SrcBitWidth);
1265 RHSKnownZero.trunc(SrcBitWidth);
1266 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001267 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 DemandedMask.zext(BitWidth);
1271 RHSKnownZero.zext(BitWidth);
1272 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001273 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001275 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001276 break;
1277 }
1278 case Instruction::SExt: {
1279 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001280 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001281
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001283 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 // If any of the sign extended bits are demanded, we know that the sign
1287 // bit is demanded.
1288 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001289 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001290
Zhou Shengd48653a2007-03-29 04:45:55 +00001291 InputDemandedBits.trunc(SrcBitWidth);
1292 RHSKnownZero.trunc(SrcBitWidth);
1293 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001294 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001297 InputDemandedBits.zext(BitWidth);
1298 RHSKnownZero.zext(BitWidth);
1299 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001300 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001301
1302 // If the sign bit of the input is known set or clear, then we know the
1303 // top bits of the result.
1304
1305 // If the input sign bit is known zero, or if the NewBits are not demanded
1306 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1310 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001311 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001312 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 }
1314 break;
1315 }
1316 case Instruction::Add: {
1317 // Figure out what the input bits are. If the top bits of the and result
1318 // are not demanded, then the add doesn't demand them from its input
1319 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001321
1322 // If there is a constant on the RHS, there are a variety of xformations
1323 // we can do.
1324 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1325 // If null, this should be simplified elsewhere. Some of the xforms here
1326 // won't work if the RHS is zero.
1327 if (RHS->isZero())
1328 break;
1329
1330 // If the top bit of the output is demanded, demand everything from the
1331 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001332 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001333
1334 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001338
1339 // If the RHS of the add has bits set that can't affect the input, reduce
1340 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001341 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001342 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001343
1344 // Avoid excess work.
1345 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1346 break;
1347
1348 // Turn it into OR if input bits are zero.
1349 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1350 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001351 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001352 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 }
1355
1356 // We can say something about the output known-zero and known-one bits,
1357 // depending on potential carries from the input constant and the
1358 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1359 // bits set and the RHS constant is 0x01001, then we know we have a known
1360 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1361
1362 // To compute this, we first compute the potential carry bits. These are
1363 // the bits which may be modified. I'm not aware of a better way to do
1364 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001366 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001367
1368 // Now that we know which bits have carries, compute the known-1/0 sets.
1369
1370 // Bits are known one if they are known zero in one operand and one in the
1371 // other, and there is no input carry.
1372 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1373 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1374
1375 // Bits are known zero if they are known zero in both operands and there
1376 // is no input carry.
1377 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1378 } else {
1379 // If the high-bits of this ADD are not demanded, then it does not demand
1380 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001381 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001382 // Right fill the mask of bits for this ADD to demand the most
1383 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001384 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001385 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1386 LHSKnownZero, LHSKnownOne, Depth+1) ||
1387 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001388 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001389 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 }
1391 }
1392 break;
1393 }
1394 case Instruction::Sub:
1395 // If the high-bits of this SUB are not demanded, then it does not demand
1396 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001397 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 // Right fill the mask of bits for this SUB to demand the most
1399 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001400 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001401 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001402 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1403 LHSKnownZero, LHSKnownOne, Depth+1) ||
1404 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001405 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001406 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001407 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001408 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1409 // the known zeros and ones.
1410 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001411 break;
1412 case Instruction::Shl:
1413 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001414 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001415 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001416 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001418 return I;
1419 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001420 RHSKnownZero <<= ShiftAmt;
1421 RHSKnownOne <<= ShiftAmt;
1422 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001423 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001424 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001425 }
1426 break;
1427 case Instruction::LShr:
1428 // For a logical shift right
1429 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001430 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001431
Reid Spencer8cb68342007-03-12 17:25:59 +00001432 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001433 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001434 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001435 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001436 return I;
1437 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001438 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1439 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001440 if (ShiftAmt) {
1441 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001442 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001443 RHSKnownZero |= HighBits; // high bits known zero.
1444 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001445 }
1446 break;
1447 case Instruction::AShr:
1448 // If this is an arithmetic shift right and only the low-bit is set, we can
1449 // always convert this into a logical shr, even if the shift amount is
1450 // variable. The low bit of the shift cannot be an input sign bit unless
1451 // the shift amount is >= the size of the datatype, which is undefined.
1452 if (DemandedMask == 1) {
1453 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001454 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001455 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001456 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001457 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001458
1459 // If the sign bit is the only bit demanded by this ashr, then there is no
1460 // need to do it, the shift doesn't change the high bit.
1461 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001462 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001463
1464 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001465 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001466
Reid Spencer8cb68342007-03-12 17:25:59 +00001467 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001468 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001469 // If any of the "high bits" are demanded, we should set the sign bit as
1470 // demanded.
1471 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1472 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001473 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001474 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001475 return I;
1476 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001477 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001478 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001479 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1480 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1481
1482 // Handle the sign bits.
1483 APInt SignBit(APInt::getSignBit(BitWidth));
1484 // Adjust to where it is now in the mask.
1485 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1486
1487 // If the input sign bit is known to be zero, or if none of the top bits
1488 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001489 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001490 (HighBits & ~DemandedMask) == HighBits) {
1491 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001492 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001493 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001494 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001495 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1496 RHSKnownOne |= HighBits;
1497 }
1498 }
1499 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001500 case Instruction::SRem:
1501 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001502 APInt RA = Rem->getValue().abs();
1503 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001504 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001505 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001506
Nick Lewycky8e394322008-11-02 02:41:50 +00001507 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001508 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001509 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001510 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001511 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001512
1513 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1514 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001515
1516 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001517
Chris Lattner886ab6c2009-01-31 08:15:18 +00001518 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001519 }
1520 }
1521 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001522 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001523 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1524 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001525 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1526 KnownZero2, KnownOne2, Depth+1) ||
1527 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001528 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001529 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001530
Chris Lattner455e9ab2009-01-21 18:09:24 +00001531 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001532 Leaders = std::max(Leaders,
1533 KnownZero2.countLeadingOnes());
1534 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001535 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001536 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001537 case Instruction::Call:
1538 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1539 switch (II->getIntrinsicID()) {
1540 default: break;
1541 case Intrinsic::bswap: {
1542 // If the only bits demanded come from one byte of the bswap result,
1543 // just shift the input byte into position to eliminate the bswap.
1544 unsigned NLZ = DemandedMask.countLeadingZeros();
1545 unsigned NTZ = DemandedMask.countTrailingZeros();
1546
1547 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1548 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1549 // have 14 leading zeros, round to 8.
1550 NLZ &= ~7;
1551 NTZ &= ~7;
1552 // If we need exactly one byte, we can do this transformation.
1553 if (BitWidth-NLZ-NTZ == 8) {
1554 unsigned ResultBit = NTZ;
1555 unsigned InputBit = BitWidth-NTZ-8;
1556
1557 // Replace this with either a left or right shift to get the byte into
1558 // the right place.
1559 Instruction *NewVal;
1560 if (InputBit > ResultBit)
1561 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001562 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001563 else
1564 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001565 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001566 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001567 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001568 }
1569
1570 // TODO: Could compute known zero/one bits based on the input.
1571 break;
1572 }
1573 }
1574 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001575 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001576 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001577 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001578
1579 // If the client is only demanding bits that we know, return the known
1580 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001581 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1582 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001583 return false;
1584}
1585
Chris Lattner867b99f2006-10-05 06:55:50 +00001586
Mon P Wangaeb06d22008-11-10 04:46:22 +00001587/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001588/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001589/// actually used by the caller. This method analyzes which elements of the
1590/// operand are undef and returns that information in UndefElts.
1591///
1592/// If the information about demanded elements can be used to simplify the
1593/// operation, the operation is simplified, then the resultant value is
1594/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001595Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1596 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001597 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001598 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001599 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001601
1602 if (isa<UndefValue>(V)) {
1603 // If the entire vector is undefined, just return this info.
1604 UndefElts = EltMask;
1605 return 0;
1606 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1607 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001608 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001609 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001610
Chris Lattner867b99f2006-10-05 06:55:50 +00001611 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001612 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1613 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001614 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001615
1616 std::vector<Constant*> Elts;
1617 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001618 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001619 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001620 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001621 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1622 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001623 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001624 } else { // Otherwise, defined.
1625 Elts.push_back(CP->getOperand(i));
1626 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001627
Chris Lattner867b99f2006-10-05 06:55:50 +00001628 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001629 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001630 return NewCP != CP ? NewCP : 0;
1631 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001632 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001633 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001634
1635 // Check if this is identity. If so, return 0 since we are not simplifying
1636 // anything.
1637 if (DemandedElts == ((1ULL << VWidth) -1))
1638 return 0;
1639
Reid Spencer9d6565a2007-02-15 02:26:10 +00001640 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001641 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001642 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001643 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001644 for (unsigned i = 0; i != VWidth; ++i) {
1645 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1646 Elts.push_back(Elt);
1647 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001648 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001649 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001650 }
1651
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652 // Limit search depth.
1653 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001654 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001655
1656 // If multiple users are using the root value, procede with
1657 // simplification conservatively assuming that all elements
1658 // are needed.
1659 if (!V->hasOneUse()) {
1660 // Quit if we find multiple users of a non-root value though.
1661 // They'll be handled when it's their turn to be visited by
1662 // the main instcombine process.
1663 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001664 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001665 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001666
1667 // Conservatively assume that all elements are needed.
1668 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001669 }
1670
1671 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001672 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001673
1674 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001675 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001676 Value *TmpV;
1677 switch (I->getOpcode()) {
1678 default: break;
1679
1680 case Instruction::InsertElement: {
1681 // If this is a variable index, we don't know which element it overwrites.
1682 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001683 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001684 if (Idx == 0) {
1685 // Note that we can't propagate undef elt info, because we don't know
1686 // which elt is getting updated.
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1688 UndefElts2, Depth+1);
1689 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1690 break;
1691 }
1692
1693 // If this is inserting an element that isn't demanded, remove this
1694 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001695 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001696 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1697 Worklist.Add(I);
1698 return I->getOperand(0);
1699 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001700
1701 // Otherwise, the element inserted overwrites whatever was there, so the
1702 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001703 APInt DemandedElts2 = DemandedElts;
1704 DemandedElts2.clear(IdxNo);
1705 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001706 UndefElts, Depth+1);
1707 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1708
1709 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001710 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001711 break;
1712 }
1713 case Instruction::ShuffleVector: {
1714 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001715 uint64_t LHSVWidth =
1716 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001717 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001718 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001719 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001720 unsigned MaskVal = Shuffle->getMaskValue(i);
1721 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001722 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001723 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001724 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001725 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001726 else
Evan Cheng388df622009-02-03 10:05:09 +00001727 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001728 }
1729 }
1730 }
1731
Nate Begeman7b254672009-02-11 22:36:25 +00001732 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001733 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001734 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001735 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1736
Nate Begeman7b254672009-02-11 22:36:25 +00001737 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001738 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1739 UndefElts3, Depth+1);
1740 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1741
1742 bool NewUndefElts = false;
1743 for (unsigned i = 0; i < VWidth; i++) {
1744 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001745 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001746 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001747 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001748 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001749 NewUndefElts = true;
1750 UndefElts.set(i);
1751 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001752 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001753 if (UndefElts3[MaskVal - LHSVWidth]) {
1754 NewUndefElts = true;
1755 UndefElts.set(i);
1756 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001757 }
1758 }
1759
1760 if (NewUndefElts) {
1761 // Add additional discovered undefs.
1762 std::vector<Constant*> Elts;
1763 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001764 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001765 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001766 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001767 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001768 Shuffle->getMaskValue(i)));
1769 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001770 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001771 MadeChange = true;
1772 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001773 break;
1774 }
Chris Lattner69878332007-04-14 22:29:23 +00001775 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001776 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001777 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1778 if (!VTy) break;
1779 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001780 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001781 unsigned Ratio;
1782
1783 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001784 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001785 // elements as are demanded of us.
1786 Ratio = 1;
1787 InputDemandedElts = DemandedElts;
1788 } else if (VWidth > InVWidth) {
1789 // Untested so far.
1790 break;
1791
1792 // If there are more elements in the result than there are in the source,
1793 // then an input element is live if any of the corresponding output
1794 // elements are live.
1795 Ratio = VWidth/InVWidth;
1796 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001797 if (DemandedElts[OutIdx])
1798 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001799 }
1800 } else {
1801 // Untested so far.
1802 break;
1803
1804 // If there are more elements in the source than there are in the result,
1805 // then an input element is live if the corresponding output element is
1806 // live.
1807 Ratio = InVWidth/VWidth;
1808 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001809 if (DemandedElts[InIdx/Ratio])
1810 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001811 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001812
Chris Lattner69878332007-04-14 22:29:23 +00001813 // div/rem demand all inputs, because they don't want divide by zero.
1814 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1815 UndefElts2, Depth+1);
1816 if (TmpV) {
1817 I->setOperand(0, TmpV);
1818 MadeChange = true;
1819 }
1820
1821 UndefElts = UndefElts2;
1822 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001823 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001824 // If there are more elements in the result than there are in the source,
1825 // then an output element is undef if the corresponding input element is
1826 // undef.
1827 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001828 if (UndefElts2[OutIdx/Ratio])
1829 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001830 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001831 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001832 // If there are more elements in the source than there are in the result,
1833 // then a result element is undef if all of the corresponding input
1834 // elements are undef.
1835 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1836 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001837 if (!UndefElts2[InIdx]) // Not undef?
1838 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001839 }
1840 break;
1841 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001842 case Instruction::And:
1843 case Instruction::Or:
1844 case Instruction::Xor:
1845 case Instruction::Add:
1846 case Instruction::Sub:
1847 case Instruction::Mul:
1848 // div/rem demand all inputs, because they don't want divide by zero.
1849 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1850 UndefElts, Depth+1);
1851 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1852 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1853 UndefElts2, Depth+1);
1854 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1855
1856 // Output elements are undefined if both are undefined. Consider things
1857 // like undef&0. The result is known zero, not undef.
1858 UndefElts &= UndefElts2;
1859 break;
1860
1861 case Instruction::Call: {
1862 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1863 if (!II) break;
1864 switch (II->getIntrinsicID()) {
1865 default: break;
1866
1867 // Binary vector operations that work column-wise. A dest element is a
1868 // function of the corresponding input elements from the two inputs.
1869 case Intrinsic::x86_sse_sub_ss:
1870 case Intrinsic::x86_sse_mul_ss:
1871 case Intrinsic::x86_sse_min_ss:
1872 case Intrinsic::x86_sse_max_ss:
1873 case Intrinsic::x86_sse2_sub_sd:
1874 case Intrinsic::x86_sse2_mul_sd:
1875 case Intrinsic::x86_sse2_min_sd:
1876 case Intrinsic::x86_sse2_max_sd:
1877 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1878 UndefElts, Depth+1);
1879 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1880 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1881 UndefElts2, Depth+1);
1882 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1883
1884 // If only the low elt is demanded and this is a scalarizable intrinsic,
1885 // scalarize it now.
1886 if (DemandedElts == 1) {
1887 switch (II->getIntrinsicID()) {
1888 default: break;
1889 case Intrinsic::x86_sse_sub_ss:
1890 case Intrinsic::x86_sse_mul_ss:
1891 case Intrinsic::x86_sse2_sub_sd:
1892 case Intrinsic::x86_sse2_mul_sd:
1893 // TODO: Lower MIN/MAX/ABS/etc
1894 Value *LHS = II->getOperand(1);
1895 Value *RHS = II->getOperand(2);
1896 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001897 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001898 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001899 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001900 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001901
1902 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001903 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001904 case Intrinsic::x86_sse_sub_ss:
1905 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001906 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001907 II->getName()), *II);
1908 break;
1909 case Intrinsic::x86_sse_mul_ss:
1910 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001911 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001912 II->getName()), *II);
1913 break;
1914 }
1915
1916 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001917 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001918 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001919 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001920 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001921 return New;
1922 }
1923 }
1924
1925 // Output elements are undefined if both are undefined. Consider things
1926 // like undef&0. The result is known zero, not undef.
1927 UndefElts &= UndefElts2;
1928 break;
1929 }
1930 break;
1931 }
1932 }
1933 return MadeChange ? I : 0;
1934}
1935
Dan Gohman45b4e482008-05-19 22:14:15 +00001936
Chris Lattner564a7272003-08-13 19:01:45 +00001937/// AssociativeOpt - Perform an optimization on an associative operator. This
1938/// function is designed to check a chain of associative operators for a
1939/// potential to apply a certain optimization. Since the optimization may be
1940/// applicable if the expression was reassociated, this checks the chain, then
1941/// reassociates the expression as necessary to expose the optimization
1942/// opportunity. This makes use of a special Functor, which must define
1943/// 'shouldApply' and 'apply' methods.
1944///
1945template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001946static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001947 unsigned Opcode = Root.getOpcode();
1948 Value *LHS = Root.getOperand(0);
1949
1950 // Quick check, see if the immediate LHS matches...
1951 if (F.shouldApply(LHS))
1952 return F.apply(Root);
1953
1954 // Otherwise, if the LHS is not of the same opcode as the root, return.
1955 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001956 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001957 // Should we apply this transform to the RHS?
1958 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1959
1960 // If not to the RHS, check to see if we should apply to the LHS...
1961 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1962 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1963 ShouldApply = true;
1964 }
1965
1966 // If the functor wants to apply the optimization to the RHS of LHSI,
1967 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1968 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001969 // Now all of the instructions are in the current basic block, go ahead
1970 // and perform the reassociation.
1971 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1972
1973 // First move the selected RHS to the LHS of the root...
1974 Root.setOperand(0, LHSI->getOperand(1));
1975
1976 // Make what used to be the LHS of the root be the user of the root...
1977 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001978 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001979 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001980 return 0;
1981 }
Chris Lattner65725312004-04-16 18:08:07 +00001982 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001983 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001984 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001985 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001986 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001987
1988 // Now propagate the ExtraOperand down the chain of instructions until we
1989 // get to LHSI.
1990 while (TmpLHSI != LHSI) {
1991 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001992 // Move the instruction to immediately before the chain we are
1993 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001994 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001995 ARI = NextLHSI;
1996
Chris Lattner564a7272003-08-13 19:01:45 +00001997 Value *NextOp = NextLHSI->getOperand(1);
1998 NextLHSI->setOperand(1, ExtraOperand);
1999 TmpLHSI = NextLHSI;
2000 ExtraOperand = NextOp;
2001 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002002
Chris Lattner564a7272003-08-13 19:01:45 +00002003 // Now that the instructions are reassociated, have the functor perform
2004 // the transformation...
2005 return F.apply(Root);
2006 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002007
Chris Lattner564a7272003-08-13 19:01:45 +00002008 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2009 }
2010 return 0;
2011}
2012
Dan Gohman844731a2008-05-13 00:00:25 +00002013namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00002014
Nick Lewycky02d639f2008-05-23 04:34:58 +00002015// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00002016struct AddRHS {
2017 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00002018 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002019 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2020 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00002021 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00002022 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00002023 }
2024};
2025
2026// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2027// iff C1&C2 == 0
2028struct AddMaskingAnd {
2029 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00002030 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00002031 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002032 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00002033 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002034 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00002035 }
2036 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002037 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00002038 }
2039};
2040
Dan Gohman844731a2008-05-13 00:00:25 +00002041}
2042
Chris Lattner6e7ba452005-01-01 16:22:27 +00002043static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00002044 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00002045 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00002046 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00002047
Chris Lattner2eefe512004-04-09 19:05:30 +00002048 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00002049 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2050 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00002051
Chris Lattner2eefe512004-04-09 19:05:30 +00002052 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2053 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00002054 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2055 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00002056 }
2057
2058 Value *Op0 = SO, *Op1 = ConstOperand;
2059 if (!ConstIsRHS)
2060 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00002061
Chris Lattner6e7ba452005-01-01 16:22:27 +00002062 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00002063 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
2064 SO->getName()+".op");
2065 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
2066 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2067 SO->getName()+".cmp");
2068 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
2069 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
2070 SO->getName()+".cmp");
2071 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00002072}
2073
2074// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2075// constant as the other operand, try to fold the binary operator into the
2076// select arguments. This also works for Cast instructions, which obviously do
2077// not have a second operand.
2078static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2079 InstCombiner *IC) {
2080 // Don't modify shared select instructions
2081 if (!SI->hasOneUse()) return 0;
2082 Value *TV = SI->getOperand(1);
2083 Value *FV = SI->getOperand(2);
2084
2085 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002086 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002087 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002088
Chris Lattner6e7ba452005-01-01 16:22:27 +00002089 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2090 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2091
Gabor Greif051a9502008-04-06 20:25:17 +00002092 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2093 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002094 }
2095 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002096}
2097
Chris Lattner4e998b22004-09-29 05:07:12 +00002098
Chris Lattner5d1704d2009-09-27 19:57:57 +00002099/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2100/// has a PHI node as operand #0, see if we can fold the instruction into the
2101/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002102///
2103/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2104/// that would normally be unprofitable because they strongly encourage jump
2105/// threading.
2106Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2107 bool AllowAggressive) {
2108 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002109 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002110 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002111 if (NumPHIValues == 0 ||
2112 // We normally only transform phis with a single use, unless we're trying
2113 // hard to make jump threading happen.
2114 (!PN->hasOneUse() && !AllowAggressive))
2115 return 0;
2116
2117
Chris Lattner5d1704d2009-09-27 19:57:57 +00002118 // Check to see if all of the operands of the PHI are simple constants
2119 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002120 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2121 // bail out. We don't do arbitrary constant expressions here because moving
2122 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002123 BasicBlock *NonConstBB = 0;
2124 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002125 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2126 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002127 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002128 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002129 NonConstBB = PN->getIncomingBlock(i);
2130
2131 // If the incoming non-constant value is in I's block, we have an infinite
2132 // loop.
2133 if (NonConstBB == I.getParent())
2134 return 0;
2135 }
2136
2137 // If there is exactly one non-constant value, we can insert a copy of the
2138 // operation in that block. However, if this is a critical edge, we would be
2139 // inserting the computation one some other paths (e.g. inside a loop). Only
2140 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002141 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002142 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2143 if (!BI || !BI->isUnconditional()) return 0;
2144 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002145
2146 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002147 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002148 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002149 InsertNewInstBefore(NewPN, *PN);
2150 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002151
2152 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002153 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2154 // We only currently try to fold the condition of a select when it is a phi,
2155 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002156 Value *TrueV = SI->getTrueValue();
2157 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002158 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002159 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002160 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002161 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2162 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002163 Value *InV = 0;
2164 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002165 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002166 } else {
2167 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002168 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2169 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002170 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002171 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002172 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002173 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002174 }
2175 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002176 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002177 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002178 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002179 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002180 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002181 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002182 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002183 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002184 } else {
2185 assert(PN->getIncomingBlock(i) == NonConstBB);
2186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002187 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002188 PN->getIncomingValue(i), C, "phitmp",
2189 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002190 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002191 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002192 CI->getPredicate(),
2193 PN->getIncomingValue(i), C, "phitmp",
2194 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002195 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002196 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002197
2198 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002199 }
2200 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002201 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002202 } else {
2203 CastInst *CI = cast<CastInst>(&I);
2204 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002205 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002206 Value *InV;
2207 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002208 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002209 } else {
2210 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002211 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002212 I.getType(), "phitmp",
2213 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002214 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002215 }
2216 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002217 }
2218 }
2219 return ReplaceInstUsesWith(I, NewPN);
2220}
2221
Chris Lattner2454a2e2008-01-29 06:52:45 +00002222
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002223/// WillNotOverflowSignedAdd - Return true if we can prove that:
2224/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2225/// This basically requires proving that the add in the original type would not
2226/// overflow to change the sign bit or have a carry out.
2227bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2228 // There are different heuristics we can use for this. Here are some simple
2229 // ones.
2230
2231 // Add has the property that adding any two 2's complement numbers can only
2232 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002233 // have at least two sign bits, we know that the addition of the two values
2234 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002235 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2236 return true;
2237
2238
2239 // If one of the operands only has one non-zero bit, and if the other operand
2240 // has a known-zero bit in a more significant place than it (not including the
2241 // sign bit) the ripple may go up to and fill the zero, but won't change the
2242 // sign. For example, (X & ~4) + 1.
2243
2244 // TODO: Implement.
2245
2246 return false;
2247}
2248
Chris Lattner2454a2e2008-01-29 06:52:45 +00002249
Chris Lattner7e708292002-06-25 16:13:24 +00002250Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002251 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002252 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002253
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002254 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2255 I.hasNoUnsignedWrap(), TD))
2256 return ReplaceInstUsesWith(I, V);
2257
2258
Chris Lattner66331a42004-04-10 22:01:55 +00002259 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002260 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002261 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002262 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002263 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002264 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002265 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002266
2267 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2268 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002269 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002270 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002271
Eli Friedman709b33d2009-07-13 22:27:52 +00002272 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002273 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002274 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002275 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002276 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002277
2278 if (isa<PHINode>(LHS))
2279 if (Instruction *NV = FoldOpIntoPhi(I))
2280 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002281
Chris Lattner4f637d42006-01-06 17:59:59 +00002282 ConstantInt *XorRHS = 0;
2283 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002284 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002285 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002286 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002287 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002288
Zhou Sheng4351c642007-04-02 08:20:41 +00002289 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002290 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2291 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002292 do {
2293 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002294 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2295 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002296 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2297 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002298 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002299 if (!MaskedValueIsZero(XorLHS,
2300 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002301 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002302 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002303 }
2304 }
2305 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002306 C0080Val = APIntOps::lshr(C0080Val, Size);
2307 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2308 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002309
Reid Spencer35c38852007-03-28 01:36:16 +00002310 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002311 // with funny bit widths then this switch statement should be removed. It
2312 // is just here to get the size of the "middle" type back up to something
2313 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002314 const Type *MiddleType = 0;
2315 switch (Size) {
2316 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002317 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2318 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2319 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002320 }
2321 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002322 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002323 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002324 }
2325 }
Chris Lattner66331a42004-04-10 22:01:55 +00002326 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002327
Owen Anderson1d0be152009-08-13 21:58:54 +00002328 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002329 return BinaryOperator::CreateXor(LHS, RHS);
2330
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002331 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002332 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002333 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002334 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002335
2336 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2337 if (RHSI->getOpcode() == Instruction::Sub)
2338 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2339 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2340 }
2341 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2342 if (LHSI->getOpcode() == Instruction::Sub)
2343 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2344 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2345 }
Robert Bocchino71698282004-07-27 21:02:21 +00002346 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002347
Chris Lattner5c4afb92002-05-08 22:46:53 +00002348 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002349 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002350 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002351 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002352 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002353 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002354 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002355 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002356 }
2357
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002359 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002360
2361 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002362 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002363 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002364 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002365
Misha Brukmanfd939082005-04-21 23:48:37 +00002366
Chris Lattner50af16a2004-11-13 19:50:12 +00002367 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002368 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002369 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002370 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002371
2372 // X*C1 + X*C2 --> X * (C1+C2)
2373 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002374 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002375 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002376 }
2377
2378 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002379 if (dyn_castFoldableMul(RHS, C2) == LHS)
2380 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002381
Chris Lattnere617c9e2007-01-05 02:17:46 +00002382 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002383 if (dyn_castNotVal(LHS) == RHS ||
2384 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002385 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002386
Chris Lattnerad3448c2003-02-18 19:57:07 +00002387
Chris Lattner564a7272003-08-13 19:01:45 +00002388 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002389 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2390 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002391 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002392
2393 // A+B --> A|B iff A and B have no bits set in common.
2394 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2395 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2396 APInt LHSKnownOne(IT->getBitWidth(), 0);
2397 APInt LHSKnownZero(IT->getBitWidth(), 0);
2398 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2399 if (LHSKnownZero != 0) {
2400 APInt RHSKnownOne(IT->getBitWidth(), 0);
2401 APInt RHSKnownZero(IT->getBitWidth(), 0);
2402 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2403
2404 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002405 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002406 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002407 }
2408 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002409
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002410 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002411 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002412 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002413 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2414 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002415 if (W != Y) {
2416 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002417 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002418 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002419 std::swap(W, X);
2420 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002421 std::swap(Y, Z);
2422 std::swap(W, X);
2423 }
2424 }
2425
2426 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002427 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002428 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002429 }
2430 }
2431 }
2432
Chris Lattner6b032052003-10-02 15:11:26 +00002433 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002434 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002435 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002436 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002437
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002438 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002439 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002440 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002441 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002442 if (Anded == CRHS) {
2443 // See if all bits from the first bit set in the Add RHS up are included
2444 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002445 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002446
2447 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002448 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002449
2450 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002451 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002452
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002453 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2454 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002455 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002456 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002457 }
2458 }
2459 }
2460
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002461 // Try to fold constant add into select arguments.
2462 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002463 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002464 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002465 }
2466
Chris Lattner42790482007-12-20 01:56:58 +00002467 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002468 {
2469 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002470 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002471 if (!SI) {
2472 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002473 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002474 }
Chris Lattner42790482007-12-20 01:56:58 +00002475 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002476 Value *TV = SI->getTrueValue();
2477 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002478 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002479
2480 // Can we fold the add into the argument of the select?
2481 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002482 if (match(FV, m_Zero()) &&
2483 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002484 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002485 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002486 if (match(TV, m_Zero()) &&
2487 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002488 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002489 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002490 }
2491 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002492
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002493 // Check for (add (sext x), y), see if we can merge this into an
2494 // integer add followed by a sext.
2495 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2496 // (add (sext x), cst) --> (sext (add x, cst'))
2497 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2498 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002499 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002500 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002501 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002502 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2503 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002504 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2505 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002506 return new SExtInst(NewAdd, I.getType());
2507 }
2508 }
2509
2510 // (add (sext x), (sext y)) --> (sext (add int x, y))
2511 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2512 // Only do this if x/y have the same type, if at last one of them has a
2513 // single use (so we don't increase the number of sexts), and if the
2514 // integer add will not overflow.
2515 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2516 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2517 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2518 RHSConv->getOperand(0))) {
2519 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002520 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2521 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002522 return new SExtInst(NewAdd, I.getType());
2523 }
2524 }
2525 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002526
2527 return Changed ? &I : 0;
2528}
2529
2530Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2531 bool Changed = SimplifyCommutative(I);
2532 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2533
2534 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2535 // X + 0 --> X
2536 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002537 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002538 (I.getType())->getValueAPF()))
2539 return ReplaceInstUsesWith(I, LHS);
2540 }
2541
2542 if (isa<PHINode>(LHS))
2543 if (Instruction *NV = FoldOpIntoPhi(I))
2544 return NV;
2545 }
2546
2547 // -A + B --> B - A
2548 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002549 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002550 return BinaryOperator::CreateFSub(RHS, LHSV);
2551
2552 // A + -B --> A - B
2553 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002554 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002555 return BinaryOperator::CreateFSub(LHS, V);
2556
2557 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2558 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2559 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2560 return ReplaceInstUsesWith(I, LHS);
2561
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002562 // Check for (add double (sitofp x), y), see if we can merge this into an
2563 // integer add followed by a promotion.
2564 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2565 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2566 // ... if the constant fits in the integer value. This is useful for things
2567 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2568 // requires a constant pool load, and generally allows the add to be better
2569 // instcombined.
2570 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2571 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002572 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002573 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002574 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002575 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2576 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002577 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2578 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002579 return new SIToFPInst(NewAdd, I.getType());
2580 }
2581 }
2582
2583 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2584 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2585 // Only do this if x/y have the same type, if at last one of them has a
2586 // single use (so we don't increase the number of int->fp conversions),
2587 // and if the integer add will not overflow.
2588 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2589 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2590 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2591 RHSConv->getOperand(0))) {
2592 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002593 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002594 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002595 return new SIToFPInst(NewAdd, I.getType());
2596 }
2597 }
2598 }
2599
Chris Lattner7e708292002-06-25 16:13:24 +00002600 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002601}
2602
Chris Lattner092543c2009-11-04 08:05:20 +00002603
2604/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2605/// code necessary to compute the offset from the base pointer (without adding
2606/// in the base pointer). Return the result as a signed integer of intptr size.
2607static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2608 TargetData &TD = *IC.getTargetData();
2609 gep_type_iterator GTI = gep_type_begin(GEP);
2610 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2611 Value *Result = Constant::getNullValue(IntPtrTy);
2612
2613 // Build a mask for high order bits.
2614 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2615 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2616
2617 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2618 ++i, ++GTI) {
2619 Value *Op = *i;
2620 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2621 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2622 if (OpC->isZero()) continue;
2623
2624 // Handle a struct index, which adds its field offset to the pointer.
2625 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2626 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2627
2628 Result = IC.Builder->CreateAdd(Result,
2629 ConstantInt::get(IntPtrTy, Size),
2630 GEP->getName()+".offs");
2631 continue;
2632 }
2633
2634 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2635 Constant *OC =
2636 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2637 Scale = ConstantExpr::getMul(OC, Scale);
2638 // Emit an add instruction.
2639 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2640 continue;
2641 }
2642 // Convert to correct type.
2643 if (Op->getType() != IntPtrTy)
2644 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2645 if (Size != 1) {
2646 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2647 // We'll let instcombine(mul) convert this to a shl if possible.
2648 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2649 }
2650
2651 // Emit an add instruction.
2652 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2653 }
2654 return Result;
2655}
2656
2657
2658/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2659/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2660/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2661/// be complex, and scales are involved. The above expression would also be
2662/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2663/// This later form is less amenable to optimization though, and we are allowed
2664/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2665///
2666/// If we can't emit an optimized form for this expression, this returns null.
2667///
2668static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2669 InstCombiner &IC) {
2670 TargetData &TD = *IC.getTargetData();
2671 gep_type_iterator GTI = gep_type_begin(GEP);
2672
2673 // Check to see if this gep only has a single variable index. If so, and if
2674 // any constant indices are a multiple of its scale, then we can compute this
2675 // in terms of the scale of the variable index. For example, if the GEP
2676 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2677 // because the expression will cross zero at the same point.
2678 unsigned i, e = GEP->getNumOperands();
2679 int64_t Offset = 0;
2680 for (i = 1; i != e; ++i, ++GTI) {
2681 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2682 // Compute the aggregate offset of constant indices.
2683 if (CI->isZero()) continue;
2684
2685 // Handle a struct index, which adds its field offset to the pointer.
2686 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2687 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2688 } else {
2689 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2690 Offset += Size*CI->getSExtValue();
2691 }
2692 } else {
2693 // Found our variable index.
2694 break;
2695 }
2696 }
2697
2698 // If there are no variable indices, we must have a constant offset, just
2699 // evaluate it the general way.
2700 if (i == e) return 0;
2701
2702 Value *VariableIdx = GEP->getOperand(i);
2703 // Determine the scale factor of the variable element. For example, this is
2704 // 4 if the variable index is into an array of i32.
2705 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2706
2707 // Verify that there are no other variable indices. If so, emit the hard way.
2708 for (++i, ++GTI; i != e; ++i, ++GTI) {
2709 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2710 if (!CI) return 0;
2711
2712 // Compute the aggregate offset of constant indices.
2713 if (CI->isZero()) continue;
2714
2715 // Handle a struct index, which adds its field offset to the pointer.
2716 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2717 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2718 } else {
2719 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2720 Offset += Size*CI->getSExtValue();
2721 }
2722 }
2723
2724 // Okay, we know we have a single variable index, which must be a
2725 // pointer/array/vector index. If there is no offset, life is simple, return
2726 // the index.
2727 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2728 if (Offset == 0) {
2729 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2730 // we don't need to bother extending: the extension won't affect where the
2731 // computation crosses zero.
2732 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2733 VariableIdx = new TruncInst(VariableIdx,
2734 TD.getIntPtrType(VariableIdx->getContext()),
2735 VariableIdx->getName(), &I);
2736 return VariableIdx;
2737 }
2738
2739 // Otherwise, there is an index. The computation we will do will be modulo
2740 // the pointer size, so get it.
2741 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2742
2743 Offset &= PtrSizeMask;
2744 VariableScale &= PtrSizeMask;
2745
2746 // To do this transformation, any constant index must be a multiple of the
2747 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2748 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2749 // multiple of the variable scale.
2750 int64_t NewOffs = Offset / (int64_t)VariableScale;
2751 if (Offset != NewOffs*(int64_t)VariableScale)
2752 return 0;
2753
2754 // Okay, we can do this evaluation. Start by converting the index to intptr.
2755 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2756 if (VariableIdx->getType() != IntPtrTy)
2757 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2758 true /*SExt*/,
2759 VariableIdx->getName(), &I);
2760 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2761 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2762}
2763
2764
2765/// Optimize pointer differences into the same array into a size. Consider:
2766/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2767/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2768///
2769Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2770 const Type *Ty) {
2771 assert(TD && "Must have target data info for this");
2772
2773 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2774 // this.
2775 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00002776 GetElementPtrInst *GEP = 0;
2777 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00002778
Chris Lattner85c1c962010-01-01 22:42:29 +00002779 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2780 // For now we require one side to be the base pointer "A" or a constant
2781 // expression derived from it.
2782 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2783 // (gep X, ...) - X
2784 if (LHSGEP->getOperand(0) == RHS) {
2785 GEP = LHSGEP;
2786 Swapped = false;
2787 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2788 // (gep X, ...) - (ce_gep X, ...)
2789 if (CE->getOpcode() == Instruction::GetElementPtr &&
2790 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2791 CstGEP = CE;
2792 GEP = LHSGEP;
2793 Swapped = false;
2794 }
2795 }
2796 }
2797
2798 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2799 // X - (gep X, ...)
2800 if (RHSGEP->getOperand(0) == LHS) {
2801 GEP = RHSGEP;
2802 Swapped = true;
2803 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2804 // (ce_gep X, ...) - (gep X, ...)
2805 if (CE->getOpcode() == Instruction::GetElementPtr &&
2806 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2807 CstGEP = CE;
2808 GEP = RHSGEP;
2809 Swapped = true;
2810 }
2811 }
2812 }
2813
2814 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00002815 return 0;
2816
Chris Lattner092543c2009-11-04 08:05:20 +00002817 // Emit the offset of the GEP and an intptr_t.
2818 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00002819
2820 // If we had a constant expression GEP on the other side offsetting the
2821 // pointer, subtract it from the offset we have.
2822 if (CstGEP) {
2823 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2824 Result = Builder->CreateSub(Result, CstOffset);
2825 }
2826
Chris Lattner092543c2009-11-04 08:05:20 +00002827
2828 // If we have p - gep(p, ...) then we have to negate the result.
2829 if (Swapped)
2830 Result = Builder->CreateNeg(Result, "diff.neg");
2831
2832 return Builder->CreateIntCast(Result, Ty, true);
2833}
2834
2835
Chris Lattner7e708292002-06-25 16:13:24 +00002836Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002837 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002838
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002839 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002840 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002841
Chris Lattner3bf68152009-12-21 04:04:05 +00002842 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2843 if (Value *V = dyn_castNegVal(Op1)) {
2844 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2845 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2846 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2847 return Res;
2848 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002849
Chris Lattnere87597f2004-10-16 18:11:37 +00002850 if (isa<UndefValue>(Op0))
2851 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2852 if (isa<UndefValue>(Op1))
2853 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002854 if (I.getType() == Type::getInt1Ty(*Context))
2855 return BinaryOperator::CreateXor(Op0, Op1);
2856
Chris Lattnerd65460f2003-11-05 01:06:05 +00002857 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002858 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002859 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002860 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002861
Chris Lattnerd65460f2003-11-05 01:06:05 +00002862 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002863 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002864 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002865 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002866
Chris Lattner76b7a062007-01-15 07:02:54 +00002867 // -(X >>u 31) -> (X >>s 31)
2868 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002869 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002870 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002871 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002872 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002873 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002874 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002875 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002876 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002877 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002878 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002879 }
2880 }
Chris Lattner092543c2009-11-04 08:05:20 +00002881 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002882 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2883 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002884 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002885 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002886 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002887 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002888 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002889 }
2890 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002891 }
2892 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002893 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002894
2895 // Try to fold constant sub into select arguments.
2896 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002898 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002899
2900 // C - zext(bool) -> bool ? C - 1 : C
2901 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002902 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002903 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002904 }
2905
Chris Lattner43d84d62005-04-07 16:15:25 +00002906 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002907 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002908 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002909 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002910 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002911 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002912 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002913 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002914 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2915 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2916 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002917 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002918 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002919 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002920 }
2921
Chris Lattnerfd059242003-10-15 16:48:29 +00002922 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002923 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2924 // is not used by anyone else...
2925 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002927 // Swap the two operands of the subexpr...
2928 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2929 Op1I->setOperand(0, IIOp1);
2930 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002931
Chris Lattnera2881962003-02-18 19:28:33 +00002932 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002933 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002934 }
2935
2936 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2937 //
2938 if (Op1I->getOpcode() == Instruction::And &&
2939 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2940 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2941
Chris Lattner74381062009-08-30 07:44:24 +00002942 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002943 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002944 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002945
Reid Spencerac5209e2006-10-16 23:08:08 +00002946 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002947 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002948 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002949 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002950 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002951 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002952 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002953
Chris Lattnerad3448c2003-02-18 19:57:07 +00002954 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002955 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002956 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002957 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002958 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002959 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002960 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002961 }
Chris Lattner40371712002-05-09 01:29:19 +00002962 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002963 }
Chris Lattnera2881962003-02-18 19:28:33 +00002964
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002965 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2966 if (Op0I->getOpcode() == Instruction::Add) {
2967 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2968 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2969 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2970 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2971 } else if (Op0I->getOpcode() == Instruction::Sub) {
2972 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002973 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002974 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002975 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002976 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002977
Chris Lattner50af16a2004-11-13 19:50:12 +00002978 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002979 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002980 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002981 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002982
Chris Lattner50af16a2004-11-13 19:50:12 +00002983 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002984 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002985 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002986 }
Chris Lattner092543c2009-11-04 08:05:20 +00002987
2988 // Optimize pointer differences into the same array into a size. Consider:
2989 // &A[10] - &A[0]: we should compile this to "10".
2990 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002991 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002992 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2993 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00002994 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2995 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002996
2997 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002998 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2999 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
3000 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
3001 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00003002 }
3003
Chris Lattner3f5b8772002-05-06 16:14:14 +00003004 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003005}
3006
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003007Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
3008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3009
3010 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00003011 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003012 return BinaryOperator::CreateFAdd(Op0, V);
3013
3014 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3015 if (Op1I->getOpcode() == Instruction::FAdd) {
3016 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00003017 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00003018 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003019 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00003020 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00003021 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003022 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003023 }
3024
3025 return 0;
3026}
3027
Chris Lattnera0141b92007-07-15 20:42:37 +00003028/// isSignBitCheck - Given an exploded icmp instruction, return true if the
3029/// comparison only checks the sign bit. If it only checks the sign bit, set
3030/// TrueIfSigned if the result of the comparison is true when the input value is
3031/// signed.
3032static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3033 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003034 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003035 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3036 TrueIfSigned = true;
3037 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003038 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3039 TrueIfSigned = true;
3040 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00003041 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3042 TrueIfSigned = false;
3043 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00003044 case ICmpInst::ICMP_UGT:
3045 // True if LHS u> RHS and RHS == high-bit-mask - 1
3046 TrueIfSigned = true;
3047 return RHS->getValue() ==
3048 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3049 case ICmpInst::ICMP_UGE:
3050 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3051 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00003052 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00003053 default:
3054 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00003055 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00003056}
3057
Chris Lattner7e708292002-06-25 16:13:24 +00003058Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003059 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003061
Chris Lattnera2498472009-10-11 21:36:10 +00003062 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003063 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003064
Chris Lattner8af304a2009-10-11 07:53:15 +00003065 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00003066 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3067 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00003068
3069 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00003070 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00003071 if (SI->getOpcode() == Instruction::Shl)
3072 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003073 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003074 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00003075
Zhou Sheng843f07672007-04-19 05:39:12 +00003076 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00003077 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00003078 if (CI->equalsInt(1)) // X * 1 == X
3079 return ReplaceInstUsesWith(I, Op0);
3080 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003081 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003082
Zhou Sheng97b52c22007-03-29 01:57:21 +00003083 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003084 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003085 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003086 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003087 }
Chris Lattnera2498472009-10-11 21:36:10 +00003088 } else if (isa<VectorType>(Op1C->getType())) {
3089 if (Op1C->isNullValue())
3090 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003091
Chris Lattnera2498472009-10-11 21:36:10 +00003092 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003093 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003094 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003095
3096 // As above, vector X*splat(1.0) -> X in all defined cases.
3097 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003098 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3099 if (CI->equalsInt(1))
3100 return ReplaceInstUsesWith(I, Op0);
3101 }
3102 }
Chris Lattnera2881962003-02-18 19:28:33 +00003103 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003104
3105 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3106 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003107 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003108 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003109 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3110 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003111 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003112
3113 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003114
3115 // Try to fold constant mul into select arguments.
3116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003117 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003118 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003119
3120 if (isa<PHINode>(Op0))
3121 if (Instruction *NV = FoldOpIntoPhi(I))
3122 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003123 }
3124
Dan Gohman186a6362009-08-12 16:04:34 +00003125 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003126 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003127 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003128
Nick Lewycky0c730792008-11-21 07:33:58 +00003129 // (X / Y) * Y = X - (X % Y)
3130 // (X / Y) * -Y = (X % Y) - X
3131 {
Chris Lattnera2498472009-10-11 21:36:10 +00003132 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003133 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3134 if (!BO ||
3135 (BO->getOpcode() != Instruction::UDiv &&
3136 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003137 Op1C = Op0;
3138 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003139 }
Chris Lattnera2498472009-10-11 21:36:10 +00003140 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003141 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003142 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003143 (BO->getOpcode() == Instruction::UDiv ||
3144 BO->getOpcode() == Instruction::SDiv)) {
3145 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3146
Dan Gohmanfa94b942009-08-12 16:33:09 +00003147 // If the division is exact, X % Y is zero.
3148 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3149 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003150 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003151 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003152 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003153 }
3154
Chris Lattner74381062009-08-30 07:44:24 +00003155 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003156 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003157 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003158 else
Chris Lattner74381062009-08-30 07:44:24 +00003159 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003160 Rem->takeName(BO);
3161
Chris Lattnera2498472009-10-11 21:36:10 +00003162 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003163 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003164 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003165 }
3166 }
3167
Chris Lattner8af304a2009-10-11 07:53:15 +00003168 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003169 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003170 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003171
Chris Lattner8af304a2009-10-11 07:53:15 +00003172 // X*(1 << Y) --> X << Y
3173 // (1 << Y)*X --> X << Y
3174 {
3175 Value *Y;
3176 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003177 return BinaryOperator::CreateShl(Op1, Y);
3178 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003179 return BinaryOperator::CreateShl(Op0, Y);
3180 }
3181
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003182 // If one of the operands of the multiply is a cast from a boolean value, then
3183 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003184 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3185 if (!isa<VectorType>(I.getType())) {
3186 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003187 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003188
Chris Lattnerd2c58362009-10-11 21:29:45 +00003189 Value *BoolCast = 0, *OtherOp = 0;
3190 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003191 BoolCast = Op0, OtherOp = Op1;
3192 else if (MaskedValueIsZero(Op1, Negative2))
3193 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003194
Chris Lattner0036e3a2009-10-11 21:22:21 +00003195 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003196 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3197 BoolCast, "tmp");
3198 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003199 }
3200 }
3201
Chris Lattner7e708292002-06-25 16:13:24 +00003202 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003203}
3204
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003205Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3206 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003207 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003208
3209 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003210 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3211 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003212 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3213 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3214 if (Op1F->isExactlyValue(1.0))
3215 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003216 } else if (isa<VectorType>(Op1C->getType())) {
3217 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003218 // As above, vector X*splat(1.0) -> X in all defined cases.
3219 if (Constant *Splat = Op1V->getSplatValue()) {
3220 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3221 if (F->isExactlyValue(1.0))
3222 return ReplaceInstUsesWith(I, Op0);
3223 }
3224 }
3225 }
3226
3227 // Try to fold constant mul into select arguments.
3228 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3230 return R;
3231
3232 if (isa<PHINode>(Op0))
3233 if (Instruction *NV = FoldOpIntoPhi(I))
3234 return NV;
3235 }
3236
Dan Gohman186a6362009-08-12 16:04:34 +00003237 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003238 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003239 return BinaryOperator::CreateFMul(Op0v, Op1v);
3240
3241 return Changed ? &I : 0;
3242}
3243
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003244/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3245/// instruction.
3246bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3247 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3248
3249 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3250 int NonNullOperand = -1;
3251 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3252 if (ST->isNullValue())
3253 NonNullOperand = 2;
3254 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3255 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3256 if (ST->isNullValue())
3257 NonNullOperand = 1;
3258
3259 if (NonNullOperand == -1)
3260 return false;
3261
3262 Value *SelectCond = SI->getOperand(0);
3263
3264 // Change the div/rem to use 'Y' instead of the select.
3265 I.setOperand(1, SI->getOperand(NonNullOperand));
3266
3267 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3268 // problem. However, the select, or the condition of the select may have
3269 // multiple uses. Based on our knowledge that the operand must be non-zero,
3270 // propagate the known value for the select into other uses of it, and
3271 // propagate a known value of the condition into its other users.
3272
3273 // If the select and condition only have a single use, don't bother with this,
3274 // early exit.
3275 if (SI->use_empty() && SelectCond->hasOneUse())
3276 return true;
3277
3278 // Scan the current block backward, looking for other uses of SI.
3279 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3280
3281 while (BBI != BBFront) {
3282 --BBI;
3283 // If we found a call to a function, we can't assume it will return, so
3284 // information from below it cannot be propagated above it.
3285 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3286 break;
3287
3288 // Replace uses of the select or its condition with the known values.
3289 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3290 I != E; ++I) {
3291 if (*I == SI) {
3292 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003293 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003294 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003295 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3296 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003297 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003298 }
3299 }
3300
3301 // If we past the instruction, quit looking for it.
3302 if (&*BBI == SI)
3303 SI = 0;
3304 if (&*BBI == SelectCond)
3305 SelectCond = 0;
3306
3307 // If we ran out of things to eliminate, break out of the loop.
3308 if (SelectCond == 0 && SI == 0)
3309 break;
3310
3311 }
3312 return true;
3313}
3314
3315
Reid Spencer1628cec2006-10-26 06:15:43 +00003316/// This function implements the transforms on div instructions that work
3317/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3318/// used by the visitors to those instructions.
3319/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003320Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003322
Chris Lattner50b2ca42008-02-19 06:12:18 +00003323 // undef / X -> 0 for integer.
3324 // undef / X -> undef for FP (the undef could be a snan).
3325 if (isa<UndefValue>(Op0)) {
3326 if (Op0->getType()->isFPOrFPVector())
3327 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003328 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003329 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003330
3331 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003332 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003333 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003334
Reid Spencer1628cec2006-10-26 06:15:43 +00003335 return 0;
3336}
Misha Brukmanfd939082005-04-21 23:48:37 +00003337
Reid Spencer1628cec2006-10-26 06:15:43 +00003338/// This function implements the transforms common to both integer division
3339/// instructions (udiv and sdiv). It is called by the visitors to those integer
3340/// division instructions.
3341/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003342Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003343 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3344
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003345 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003346 if (Op0 == Op1) {
3347 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003348 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003349 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003350 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003351 }
3352
Owen Andersoneed707b2009-07-24 23:12:02 +00003353 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003354 return ReplaceInstUsesWith(I, CI);
3355 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003356
Reid Spencer1628cec2006-10-26 06:15:43 +00003357 if (Instruction *Common = commonDivTransforms(I))
3358 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003359
3360 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3361 // This does not apply for fdiv.
3362 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3363 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003364
3365 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3366 // div X, 1 == X
3367 if (RHS->equalsInt(1))
3368 return ReplaceInstUsesWith(I, Op0);
3369
3370 // (X / C1) / C2 -> X / (C1*C2)
3371 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3372 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3373 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003374 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003375 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003377 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003378 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003379 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003380 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003381
Reid Spencerbca0e382007-03-23 20:05:17 +00003382 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003383 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3384 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3385 return R;
3386 if (isa<PHINode>(Op0))
3387 if (Instruction *NV = FoldOpIntoPhi(I))
3388 return NV;
3389 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003390 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003391
Chris Lattnera2881962003-02-18 19:28:33 +00003392 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003393 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003394 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003395 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003396
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003397 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003398 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003399 return ReplaceInstUsesWith(I, Op0);
3400
Nick Lewycky895f0852008-11-27 20:21:08 +00003401 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3402 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3403 // div X, 1 == X
3404 if (X->isOne())
3405 return ReplaceInstUsesWith(I, Op0);
3406 }
3407
Reid Spencer1628cec2006-10-26 06:15:43 +00003408 return 0;
3409}
3410
3411Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3412 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3413
3414 // Handle the integer div common cases
3415 if (Instruction *Common = commonIDivTransforms(I))
3416 return Common;
3417
Reid Spencer1628cec2006-10-26 06:15:43 +00003418 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003419 // X udiv C^2 -> X >> C
3420 // Check to see if this is an unsigned division with an exact power of 2,
3421 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003422 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003423 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003424 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003425
3426 // X udiv C, where C >= signbit
3427 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003428 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003429 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003430 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003431 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003432 }
3433
3434 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003435 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003436 if (RHSI->getOpcode() == Instruction::Shl &&
3437 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003438 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003439 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003440 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003441 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003442 if (uint32_t C2 = C1.logBase2())
3443 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003444 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003445 }
3446 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003447 }
3448
Reid Spencer1628cec2006-10-26 06:15:43 +00003449 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3450 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003451 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003452 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003453 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003454 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003455 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003456 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003457 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003458 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003459 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003460 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003461
3462 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003463 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003464 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003465
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003466 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003467 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003468 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003469 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003470 return 0;
3471}
3472
Reid Spencer1628cec2006-10-26 06:15:43 +00003473Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3474 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3475
3476 // Handle the integer div common cases
3477 if (Instruction *Common = commonIDivTransforms(I))
3478 return Common;
3479
3480 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3481 // sdiv X, -1 == -X
3482 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003483 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003484
Dan Gohmanfa94b942009-08-12 16:33:09 +00003485 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003486 if (cast<SDivOperator>(&I)->isExact() &&
3487 RHS->getValue().isNonNegative() &&
3488 RHS->getValue().isPowerOf2()) {
3489 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3490 RHS->getValue().exactLogBase2());
3491 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3492 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003493
3494 // -X/C --> X/-C provided the negation doesn't overflow.
3495 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3496 if (isa<Constant>(Sub->getOperand(0)) &&
3497 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003498 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003499 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3500 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003501 }
3502
3503 // If the sign bits of both operands are zero (i.e. we can prove they are
3504 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003505 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003506 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003507 if (MaskedValueIsZero(Op0, Mask)) {
3508 if (MaskedValueIsZero(Op1, Mask)) {
3509 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3510 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3511 }
3512 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003513 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003514 ShiftedInt->getValue().isPowerOf2()) {
3515 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3516 // Safe because the only negative value (1 << Y) can take on is
3517 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3518 // the sign bit set.
3519 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3520 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003521 }
Eli Friedman8be17392009-07-18 09:53:21 +00003522 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003523
3524 return 0;
3525}
3526
3527Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3528 return commonDivTransforms(I);
3529}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003530
Reid Spencer0a783f72006-11-02 01:53:59 +00003531/// This function implements the transforms on rem instructions that work
3532/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3533/// is used by the visitors to those instructions.
3534/// @brief Transforms common to all three rem instructions
3535Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003536 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003537
Chris Lattner50b2ca42008-02-19 06:12:18 +00003538 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3539 if (I.getType()->isFPOrFPVector())
3540 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003542 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003543 if (isa<UndefValue>(Op1))
3544 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003545
3546 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003547 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3548 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003549
Reid Spencer0a783f72006-11-02 01:53:59 +00003550 return 0;
3551}
3552
3553/// This function implements the transforms common to both integer remainder
3554/// instructions (urem and srem). It is called by the visitors to those integer
3555/// remainder instructions.
3556/// @brief Common integer remainder transforms
3557Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3558 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3559
3560 if (Instruction *common = commonRemTransforms(I))
3561 return common;
3562
Dale Johannesened6af242009-01-21 00:35:19 +00003563 // 0 % X == 0 for integer, we don't need to preserve faults!
3564 if (Constant *LHS = dyn_cast<Constant>(Op0))
3565 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003566 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003567
Chris Lattner857e8cd2004-12-12 21:48:58 +00003568 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003569 // X % 0 == undef, we don't need to preserve faults!
3570 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003571 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003572
Chris Lattnera2881962003-02-18 19:28:33 +00003573 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003574 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003575
Chris Lattner97943922006-02-28 05:49:21 +00003576 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3577 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3579 return R;
3580 } else if (isa<PHINode>(Op0I)) {
3581 if (Instruction *NV = FoldOpIntoPhi(I))
3582 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003583 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003584
3585 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003586 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003587 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003588 }
Chris Lattnera2881962003-02-18 19:28:33 +00003589 }
3590
Reid Spencer0a783f72006-11-02 01:53:59 +00003591 return 0;
3592}
3593
3594Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3595 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3596
3597 if (Instruction *common = commonIRemTransforms(I))
3598 return common;
3599
3600 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3601 // X urem C^2 -> X and C
3602 // Check to see if this is an unsigned remainder with an exact power of 2,
3603 // if so, convert to a bitwise and.
3604 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003605 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003606 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003607 }
3608
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003609 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003610 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3611 if (RHSI->getOpcode() == Instruction::Shl &&
3612 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003613 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003614 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003615 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003616 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003617 }
3618 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003619 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003620
Reid Spencer0a783f72006-11-02 01:53:59 +00003621 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3622 // where C1&C2 are powers of two.
3623 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3624 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3625 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3626 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003627 if ((STO->getValue().isPowerOf2()) &&
3628 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003629 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3630 SI->getName()+".t");
3631 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3632 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003633 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003634 }
3635 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003636 }
3637
Chris Lattner3f5b8772002-05-06 16:14:14 +00003638 return 0;
3639}
3640
Reid Spencer0a783f72006-11-02 01:53:59 +00003641Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3642 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3643
Dan Gohmancff55092007-11-05 23:16:33 +00003644 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003645 if (Instruction *Common = commonIRemTransforms(I))
3646 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003647
Dan Gohman186a6362009-08-12 16:04:34 +00003648 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003649 if (!isa<Constant>(RHSNeg) ||
3650 (isa<ConstantInt>(RHSNeg) &&
3651 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003652 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003653 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003654 I.setOperand(1, RHSNeg);
3655 return &I;
3656 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003657
Dan Gohmancff55092007-11-05 23:16:33 +00003658 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003659 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003660 if (I.getType()->isInteger()) {
3661 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3662 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3663 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003664 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003665 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003666 }
3667
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003668 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003669 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3670 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003671
Nick Lewycky9dce8732008-12-20 16:48:00 +00003672 bool hasNegative = false;
3673 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3674 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3675 if (RHS->getValue().isNegative())
3676 hasNegative = true;
3677
3678 if (hasNegative) {
3679 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003680 for (unsigned i = 0; i != VWidth; ++i) {
3681 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3682 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003683 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003684 else
3685 Elts[i] = RHS;
3686 }
3687 }
3688
Owen Andersonaf7ec972009-07-28 21:19:26 +00003689 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003690 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003691 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003692 I.setOperand(1, NewRHSV);
3693 return &I;
3694 }
3695 }
3696 }
3697
Reid Spencer0a783f72006-11-02 01:53:59 +00003698 return 0;
3699}
3700
3701Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003702 return commonRemTransforms(I);
3703}
3704
Chris Lattner457dd822004-06-09 07:59:58 +00003705// isOneBitSet - Return true if there is exactly one bit set in the specified
3706// constant.
3707static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003708 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003709}
3710
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003711// isHighOnes - Return true if the constant is of the form 1+0+.
3712// This is the same as lowones(~X).
3713static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003714 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003715}
3716
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003718/// are carefully arranged to allow folding of expressions such as:
3719///
3720/// (A < B) | (A > B) --> (A != B)
3721///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003722/// Note that this is only valid if the first and second predicates have the
3723/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003724///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725/// Three bits are used to represent the condition, as follows:
3726/// 0 A > B
3727/// 1 A == B
3728/// 2 A < B
3729///
3730/// <=> Value Definition
3731/// 000 0 Always false
3732/// 001 1 A > B
3733/// 010 2 A == B
3734/// 011 3 A >= B
3735/// 100 4 A < B
3736/// 101 5 A != B
3737/// 110 6 A <= B
3738/// 111 7 Always true
3739///
3740static unsigned getICmpCode(const ICmpInst *ICI) {
3741 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003742 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003743 case ICmpInst::ICMP_UGT: return 1; // 001
3744 case ICmpInst::ICMP_SGT: return 1; // 001
3745 case ICmpInst::ICMP_EQ: return 2; // 010
3746 case ICmpInst::ICMP_UGE: return 3; // 011
3747 case ICmpInst::ICMP_SGE: return 3; // 011
3748 case ICmpInst::ICMP_ULT: return 4; // 100
3749 case ICmpInst::ICMP_SLT: return 4; // 100
3750 case ICmpInst::ICMP_NE: return 5; // 101
3751 case ICmpInst::ICMP_ULE: return 6; // 110
3752 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003753 // True -> 7
3754 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003755 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003756 return 0;
3757 }
3758}
3759
Evan Cheng8db90722008-10-14 17:15:11 +00003760/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3761/// predicate into a three bit mask. It also returns whether it is an ordered
3762/// predicate by reference.
3763static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3764 isOrdered = false;
3765 switch (CC) {
3766 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3767 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003768 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3769 case FCmpInst::FCMP_UGT: return 1; // 001
3770 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3771 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003772 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3773 case FCmpInst::FCMP_UGE: return 3; // 011
3774 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3775 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003776 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3777 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003778 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3779 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003780 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003781 default:
3782 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003783 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003784 return 0;
3785 }
3786}
3787
Reid Spencere4d87aa2006-12-23 06:05:41 +00003788/// getICmpValue - This is the complement of getICmpCode, which turns an
3789/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003790/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003791/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003792static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003793 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003794 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003795 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003796 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003797 case 1:
3798 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003799 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003800 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003801 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3802 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003803 case 3:
3804 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003805 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003806 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003807 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003808 case 4:
3809 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003810 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003811 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003812 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3813 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003814 case 6:
3815 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003816 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003817 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003818 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003819 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003820 }
3821}
3822
Evan Cheng8db90722008-10-14 17:15:11 +00003823/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3824/// opcode and two operands into either a FCmp instruction. isordered is passed
3825/// in to determine which kind of predicate to use in the new fcmp instruction.
3826static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003827 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003828 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003829 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003830 case 0:
3831 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003832 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003833 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003834 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003835 case 1:
3836 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003837 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003838 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003839 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003840 case 2:
3841 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003842 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003843 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003844 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003845 case 3:
3846 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003847 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003848 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003849 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003850 case 4:
3851 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003852 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003853 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003854 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003855 case 5:
3856 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003857 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003858 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003859 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003860 case 6:
3861 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003862 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003863 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003864 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003865 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003866 }
3867}
3868
Chris Lattnerb9553d62008-11-16 04:55:20 +00003869/// PredicatesFoldable - Return true if both predicates match sign or if at
3870/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003871static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003872 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3873 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3874 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003875}
3876
3877namespace {
3878// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3879struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003880 InstCombiner &IC;
3881 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003882 ICmpInst::Predicate pred;
3883 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3884 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3885 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003886 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003887 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3888 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003889 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3890 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003891 return false;
3892 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003893 Instruction *apply(Instruction &Log) const {
3894 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3895 if (ICI->getOperand(0) != LHS) {
3896 assert(ICI->getOperand(1) == LHS);
3897 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003898 }
3899
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003900 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003901 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003902 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003903 unsigned Code;
3904 switch (Log.getOpcode()) {
3905 case Instruction::And: Code = LHSCode & RHSCode; break;
3906 case Instruction::Or: Code = LHSCode | RHSCode; break;
3907 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003908 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003909 }
3910
Nick Lewycky4a134af2009-10-25 05:20:17 +00003911 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003912 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003913 if (Instruction *I = dyn_cast<Instruction>(RV))
3914 return I;
3915 // Otherwise, it's a constant boolean value...
3916 return IC.ReplaceInstUsesWith(Log, RV);
3917 }
3918};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003919} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003920
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003921// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3922// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003923// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003924Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003925 ConstantInt *OpRHS,
3926 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003927 BinaryOperator &TheAnd) {
3928 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003929 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003930 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003931 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003932
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003933 switch (Op->getOpcode()) {
3934 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003935 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003936 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003937 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003938 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003939 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003940 }
3941 break;
3942 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003943 if (Together == AndRHS) // (X | C) & C --> C
3944 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003945
Chris Lattner6e7ba452005-01-01 16:22:27 +00003946 if (Op->hasOneUse() && Together != OpRHS) {
3947 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003948 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003949 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003950 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003951 }
3952 break;
3953 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003954 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003955 // Adding a one to a single bit bit-field should be turned into an XOR
3956 // of the bit. First thing to check is to see if this AND is with a
3957 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003958 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003959
3960 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003961 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003962 // Ok, at this point, we know that we are masking the result of the
3963 // ADD down to exactly one bit. If the constant we are adding has
3964 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003965 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003966
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003967 // Check to see if any bits below the one bit set in AndRHSV are set.
3968 if ((AddRHS & (AndRHSV-1)) == 0) {
3969 // If not, the only thing that can effect the output of the AND is
3970 // the bit specified by AndRHSV. If that bit is set, the effect of
3971 // the XOR is to toggle the bit. If it is clear, then the ADD has
3972 // no effect.
3973 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3974 TheAnd.setOperand(0, X);
3975 return &TheAnd;
3976 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003977 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003978 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003979 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003980 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003981 }
3982 }
3983 }
3984 }
3985 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003986
3987 case Instruction::Shl: {
3988 // We know that the AND will not produce any of the bits shifted in, so if
3989 // the anded constant includes them, clear them now!
3990 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003991 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003992 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003993 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003994 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003995
Zhou Sheng290bec52007-03-29 08:15:12 +00003996 if (CI->getValue() == ShlMask) {
3997 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003998 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3999 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00004000 TheAnd.setOperand(1, CI);
4001 return &TheAnd;
4002 }
4003 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00004004 }
Reid Spencer3822ff52006-11-08 06:47:33 +00004005 case Instruction::LShr:
4006 {
Chris Lattner62a355c2003-09-19 19:05:02 +00004007 // We know that the AND will not produce any of the bits shifted in, so if
4008 // the anded constant includes them, clear them now! This only applies to
4009 // unsigned shifts, because a signed shr may bring in set bits!
4010 //
Zhou Sheng290bec52007-03-29 08:15:12 +00004011 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004012 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00004013 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00004014 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00004015
Zhou Sheng290bec52007-03-29 08:15:12 +00004016 if (CI->getValue() == ShrMask) {
4017 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00004018 return ReplaceInstUsesWith(TheAnd, Op);
4019 } else if (CI != AndRHS) {
4020 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
4021 return &TheAnd;
4022 }
4023 break;
4024 }
4025 case Instruction::AShr:
4026 // Signed shr.
4027 // See if this is shifting in some sign extension, then masking it out
4028 // with an and.
4029 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00004030 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00004031 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00004032 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00004033 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00004034 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00004035 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00004036 // Make the argument unsigned.
4037 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00004038 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004039 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00004040 }
Chris Lattner62a355c2003-09-19 19:05:02 +00004041 }
4042 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004043 }
4044 return 0;
4045}
4046
Chris Lattner8b170942002-08-09 23:47:40 +00004047
Chris Lattnera96879a2004-09-29 17:40:11 +00004048/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
4049/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00004050/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
4051/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00004052/// insert new instructions.
4053Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00004054 bool isSigned, bool Inside,
4055 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00004056 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00004057 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00004058 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004059
Chris Lattnera96879a2004-09-29 17:40:11 +00004060 if (Inside) {
4061 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004062 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00004063
Reid Spencere4d87aa2006-12-23 06:05:41 +00004064 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004065 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00004066 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00004067 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004068 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004069 }
4070
4071 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00004072 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00004073 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004074 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004075 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004076 }
4077
4078 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004079 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00004080
Reid Spencere4e40032007-03-21 23:19:50 +00004081 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00004082 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004083 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004084 ICmpInst::Predicate pred = (isSigned ?
4085 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004086 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004087 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004088
Reid Spencere4e40032007-03-21 23:19:50 +00004089 // Emit V-Lo >u Hi-1-Lo
4090 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004091 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004092 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004093 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004094 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004095}
4096
Chris Lattner7203e152005-09-18 07:22:02 +00004097// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4098// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4099// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4100// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004101static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004102 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004103 uint32_t BitWidth = Val->getType()->getBitWidth();
4104 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004105
4106 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004107 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004108 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004109 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004110 return true;
4111}
4112
Chris Lattner7203e152005-09-18 07:22:02 +00004113/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4114/// where isSub determines whether the operator is a sub. If we can fold one of
4115/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004116///
4117/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4118/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4119/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4120///
4121/// return (A +/- B).
4122///
4123Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004124 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004125 Instruction &I) {
4126 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4127 if (!LHSI || LHSI->getNumOperands() != 2 ||
4128 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4129
4130 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4131
4132 switch (LHSI->getOpcode()) {
4133 default: return 0;
4134 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004135 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004136 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004137 if ((Mask->getValue().countLeadingZeros() +
4138 Mask->getValue().countPopulation()) ==
4139 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004140 break;
4141
4142 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4143 // part, we don't need any explicit masks to take them out of A. If that
4144 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004145 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004146 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004147 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004148 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004149 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004150 break;
4151 }
4152 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004153 return 0;
4154 case Instruction::Or:
4155 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004156 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004157 if ((Mask->getValue().countLeadingZeros() +
4158 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004159 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004160 break;
4161 return 0;
4162 }
4163
Chris Lattnerc8e77562005-09-18 04:24:45 +00004164 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004165 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4166 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004167}
4168
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004169/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4170Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4171 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004172 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004173 ConstantInt *LHSCst, *RHSCst;
4174 ICmpInst::Predicate LHSCC, RHSCC;
4175
Chris Lattnerea065fb2008-11-16 05:10:52 +00004176 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004177 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004178 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004179 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004180 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004181 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004182
Chris Lattner3f40e232009-11-29 00:51:17 +00004183 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4184 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4185 // where C is a power of 2
4186 if (LHSCC == ICmpInst::ICMP_ULT &&
4187 LHSCst->getValue().isPowerOf2()) {
4188 Value *NewOr = Builder->CreateOr(Val, Val2);
4189 return new ICmpInst(LHSCC, NewOr, LHSCst);
4190 }
4191
4192 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4193 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4194 Value *NewOr = Builder->CreateOr(Val, Val2);
4195 return new ICmpInst(LHSCC, NewOr, LHSCst);
4196 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004197 }
4198
4199 // From here on, we only handle:
4200 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4201 if (Val != Val2) return 0;
4202
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004203 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4204 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4205 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4206 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4207 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4208 return 0;
4209
4210 // We can't fold (ugt x, C) & (sgt x, C2).
4211 if (!PredicatesFoldable(LHSCC, RHSCC))
4212 return 0;
4213
4214 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004215 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004216 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004217 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004218 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004219 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004220 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004221 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4222
4223 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004224 std::swap(LHS, RHS);
4225 std::swap(LHSCst, RHSCst);
4226 std::swap(LHSCC, RHSCC);
4227 }
4228
4229 // At this point, we know we have have two icmp instructions
4230 // comparing a value against two constants and and'ing the result
4231 // together. Because of the above check, we know that we only have
4232 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4233 // (from the FoldICmpLogical check above), that the two constants
4234 // are not equal and that the larger constant is on the RHS
4235 assert(LHSCst != RHSCst && "Compares not folded above?");
4236
4237 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004238 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004239 case ICmpInst::ICMP_EQ:
4240 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004241 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004242 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4243 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4244 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004245 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004246 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4247 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4248 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4249 return ReplaceInstUsesWith(I, LHS);
4250 }
4251 case ICmpInst::ICMP_NE:
4252 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004253 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004254 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004255 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004256 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004257 break; // (X != 13 & X u< 15) -> no change
4258 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004259 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004260 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004261 break; // (X != 13 & X s< 15) -> no change
4262 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4263 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4264 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4265 return ReplaceInstUsesWith(I, RHS);
4266 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004267 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004268 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004269 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004270 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004271 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004272 }
4273 break; // (X != 13 & X != 15) -> no change
4274 }
4275 break;
4276 case ICmpInst::ICMP_ULT:
4277 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004278 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004279 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4280 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004281 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004282 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4283 break;
4284 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4285 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4286 return ReplaceInstUsesWith(I, LHS);
4287 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4288 break;
4289 }
4290 break;
4291 case ICmpInst::ICMP_SLT:
4292 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004293 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004294 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4295 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004296 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004297 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4298 break;
4299 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4300 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4301 return ReplaceInstUsesWith(I, LHS);
4302 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4303 break;
4304 }
4305 break;
4306 case ICmpInst::ICMP_UGT:
4307 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004308 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004309 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4310 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4311 return ReplaceInstUsesWith(I, RHS);
4312 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4313 break;
4314 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004315 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004316 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004317 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004318 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004319 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004320 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004321 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4322 break;
4323 }
4324 break;
4325 case ICmpInst::ICMP_SGT:
4326 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004327 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004328 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4329 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4330 return ReplaceInstUsesWith(I, RHS);
4331 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4332 break;
4333 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004334 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004335 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004336 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004337 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004338 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004339 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004340 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4341 break;
4342 }
4343 break;
4344 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004345
4346 return 0;
4347}
4348
Chris Lattner42d1be02009-07-23 05:14:02 +00004349Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4350 FCmpInst *RHS) {
4351
4352 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4353 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4354 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4355 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4356 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4357 // If either of the constants are nans, then the whole thing returns
4358 // false.
4359 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004360 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004361 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004362 LHS->getOperand(0), RHS->getOperand(0));
4363 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004364
4365 // Handle vector zeros. This occurs because the canonical form of
4366 // "fcmp ord x,x" is "fcmp ord x, 0".
4367 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4368 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004369 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004370 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004371 return 0;
4372 }
4373
4374 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4375 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4376 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4377
4378
4379 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4380 // Swap RHS operands to match LHS.
4381 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4382 std::swap(Op1LHS, Op1RHS);
4383 }
4384
4385 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4386 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4387 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004388 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004389
4390 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004391 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004392 if (Op0CC == FCmpInst::FCMP_TRUE)
4393 return ReplaceInstUsesWith(I, RHS);
4394 if (Op1CC == FCmpInst::FCMP_TRUE)
4395 return ReplaceInstUsesWith(I, LHS);
4396
4397 bool Op0Ordered;
4398 bool Op1Ordered;
4399 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4400 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4401 if (Op1Pred == 0) {
4402 std::swap(LHS, RHS);
4403 std::swap(Op0Pred, Op1Pred);
4404 std::swap(Op0Ordered, Op1Ordered);
4405 }
4406 if (Op0Pred == 0) {
4407 // uno && ueq -> uno && (uno || eq) -> ueq
4408 // ord && olt -> ord && (ord && lt) -> olt
4409 if (Op0Ordered == Op1Ordered)
4410 return ReplaceInstUsesWith(I, RHS);
4411
4412 // uno && oeq -> uno && (ord && eq) -> false
4413 // uno && ord -> false
4414 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004415 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004416 // ord && ueq -> ord && (uno || eq) -> oeq
4417 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4418 Op0LHS, Op0RHS, Context));
4419 }
4420 }
4421
4422 return 0;
4423}
4424
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004425
Chris Lattner7e708292002-06-25 16:13:24 +00004426Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004427 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004428 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004429
Chris Lattnerd06094f2009-11-10 00:55:12 +00004430 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4431 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004432
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004433 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004434 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004435 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00004436 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00004437
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004438 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004439 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004440 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004441
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004442 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004443 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004444 Value *Op0LHS = Op0I->getOperand(0);
4445 Value *Op0RHS = Op0I->getOperand(1);
4446 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004447 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004448 case Instruction::Xor:
4449 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004450 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004451 if (!Op0I->hasOneUse()) break;
4452
4453 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4454 // Not masking anything out for the LHS, move to RHS.
4455 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4456 Op0RHS->getName()+".masked");
4457 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4458 }
4459 if (!isa<Constant>(Op0RHS) &&
4460 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4461 // Not masking anything out for the RHS, move to LHS.
4462 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4463 Op0LHS->getName()+".masked");
4464 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004465 }
4466
Chris Lattner6e7ba452005-01-01 16:22:27 +00004467 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004468 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004469 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4470 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4471 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4472 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004473 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004474 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004475 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004476 break;
4477
4478 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004479 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4480 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4481 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4482 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004483 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004484
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004485 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4486 // has 1's for all bits that the subtraction with A might affect.
4487 if (Op0I->hasOneUse()) {
4488 uint32_t BitWidth = AndRHSMask.getBitWidth();
4489 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4490 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4491
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004492 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004493 if (!(A && A->isZero()) && // avoid infinite recursion.
4494 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004495 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004496 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4497 }
4498 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004499 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004500
4501 case Instruction::Shl:
4502 case Instruction::LShr:
4503 // (1 << x) & 1 --> zext(x == 0)
4504 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004505 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004506 Value *NewICmp =
4507 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004508 return new ZExtInst(NewICmp, I.getType());
4509 }
4510 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004511 }
4512
Chris Lattner58403262003-07-23 19:25:52 +00004513 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004514 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004515 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004516 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004517 // If this is an integer truncation or change from signed-to-unsigned, and
4518 // if the source is an and/or with immediate, transform it. This
4519 // frequently occurs for bitfield accesses.
4520 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004521 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004522 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004523 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004524 if (CastOp->getOpcode() == Instruction::And) {
4525 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004526 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4527 // This will fold the two constants together, which may allow
4528 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004529 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004530 CastOp->getOperand(0), I.getType(),
4531 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004532 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004533 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004534 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004535 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004536 } else if (CastOp->getOpcode() == Instruction::Or) {
4537 // Change: and (cast (or X, C1) to T), C2
4538 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004539 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004540 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004541 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004542 return ReplaceInstUsesWith(I, AndRHS);
4543 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004544 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004545 }
Chris Lattner06782f82003-07-23 19:36:21 +00004546 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004547
4548 // Try to fold constant and into select arguments.
4549 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004550 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004551 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004552 if (isa<PHINode>(Op0))
4553 if (Instruction *NV = FoldOpIntoPhi(I))
4554 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004555 }
4556
Chris Lattner5b62aa72004-06-18 06:07:51 +00004557
Misha Brukmancb6267b2004-07-30 12:50:08 +00004558 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004559 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4560 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4561 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4562 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4563 I.getName()+".demorgan");
4564 return BinaryOperator::CreateNot(Or);
4565 }
4566
Chris Lattner2082ad92006-02-13 23:07:23 +00004567 {
Chris Lattner003b6202007-06-15 05:58:24 +00004568 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004569 // (A|B) & ~(A&B) -> A^B
4570 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4571 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4572 ((A == C && B == D) || (A == D && B == C)))
4573 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004574
Chris Lattnerd06094f2009-11-10 00:55:12 +00004575 // ~(A&B) & (A|B) -> A^B
4576 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4577 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4578 ((A == C && B == D) || (A == D && B == C)))
4579 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004580
4581 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004582 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004583 if (A == Op1) { // (A^B)&A -> A&(A^B)
4584 I.swapOperands(); // Simplify below
4585 std::swap(Op0, Op1);
4586 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4587 cast<BinaryOperator>(Op0)->swapOperands();
4588 I.swapOperands(); // Simplify below
4589 std::swap(Op0, Op1);
4590 }
4591 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004592
Chris Lattner64daab52006-04-01 08:03:55 +00004593 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004594 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004595 if (B == Op0) { // B&(A^B) -> B&(B^A)
4596 cast<BinaryOperator>(Op1)->swapOperands();
4597 std::swap(A, B);
4598 }
Chris Lattner74381062009-08-30 07:44:24 +00004599 if (A == Op0) // A&(A^B) -> A & ~B
4600 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004601 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004602
4603 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004604 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4605 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004606 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004607 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4608 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004609 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004610 }
4611
Reid Spencere4d87aa2006-12-23 06:05:41 +00004612 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4613 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004614 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004615 return R;
4616
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004617 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4618 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4619 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004620 }
4621
Chris Lattner6fc205f2006-05-05 06:39:07 +00004622 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004623 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4624 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4625 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4626 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004627 if (SrcTy == Op1C->getOperand(0)->getType() &&
4628 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004629 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004630 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4631 I.getType(), TD) &&
4632 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4633 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004634 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4635 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004636 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004637 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004638 }
Chris Lattnere511b742006-11-14 07:46:50 +00004639
4640 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004641 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4642 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4643 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004644 SI0->getOperand(1) == SI1->getOperand(1) &&
4645 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004646 Value *NewOp =
4647 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4648 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004649 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004650 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004651 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004652 }
4653
Evan Cheng8db90722008-10-14 17:15:11 +00004654 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004655 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004656 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4657 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4658 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004659 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004660
Chris Lattner7e708292002-06-25 16:13:24 +00004661 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004662}
4663
Chris Lattner8c34cd22008-10-05 02:13:19 +00004664/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4665/// capable of providing pieces of a bswap. The subexpression provides pieces
4666/// of a bswap if it is proven that each of the non-zero bytes in the output of
4667/// the expression came from the corresponding "byte swapped" byte in some other
4668/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4669/// we know that the expression deposits the low byte of %X into the high byte
4670/// of the bswap result and that all other bytes are zero. This expression is
4671/// accepted, the high byte of ByteValues is set to X to indicate a correct
4672/// match.
4673///
4674/// This function returns true if the match was unsuccessful and false if so.
4675/// On entry to the function the "OverallLeftShift" is a signed integer value
4676/// indicating the number of bytes that the subexpression is later shifted. For
4677/// example, if the expression is later right shifted by 16 bits, the
4678/// OverallLeftShift value would be -2 on entry. This is used to specify which
4679/// byte of ByteValues is actually being set.
4680///
4681/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4682/// byte is masked to zero by a user. For example, in (X & 255), X will be
4683/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4684/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4685/// always in the local (OverallLeftShift) coordinate space.
4686///
4687static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4688 SmallVector<Value*, 8> &ByteValues) {
4689 if (Instruction *I = dyn_cast<Instruction>(V)) {
4690 // If this is an or instruction, it may be an inner node of the bswap.
4691 if (I->getOpcode() == Instruction::Or) {
4692 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4693 ByteValues) ||
4694 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4695 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004696 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004697
4698 // If this is a logical shift by a constant multiple of 8, recurse with
4699 // OverallLeftShift and ByteMask adjusted.
4700 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4701 unsigned ShAmt =
4702 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4703 // Ensure the shift amount is defined and of a byte value.
4704 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4705 return true;
4706
4707 unsigned ByteShift = ShAmt >> 3;
4708 if (I->getOpcode() == Instruction::Shl) {
4709 // X << 2 -> collect(X, +2)
4710 OverallLeftShift += ByteShift;
4711 ByteMask >>= ByteShift;
4712 } else {
4713 // X >>u 2 -> collect(X, -2)
4714 OverallLeftShift -= ByteShift;
4715 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004716 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004717 }
4718
4719 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4720 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4721
4722 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4723 ByteValues);
4724 }
4725
4726 // If this is a logical 'and' with a mask that clears bytes, clear the
4727 // corresponding bytes in ByteMask.
4728 if (I->getOpcode() == Instruction::And &&
4729 isa<ConstantInt>(I->getOperand(1))) {
4730 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4731 unsigned NumBytes = ByteValues.size();
4732 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4733 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4734
4735 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4736 // If this byte is masked out by a later operation, we don't care what
4737 // the and mask is.
4738 if ((ByteMask & (1 << i)) == 0)
4739 continue;
4740
4741 // If the AndMask is all zeros for this byte, clear the bit.
4742 APInt MaskB = AndMask & Byte;
4743 if (MaskB == 0) {
4744 ByteMask &= ~(1U << i);
4745 continue;
4746 }
4747
4748 // If the AndMask is not all ones for this byte, it's not a bytezap.
4749 if (MaskB != Byte)
4750 return true;
4751
4752 // Otherwise, this byte is kept.
4753 }
4754
4755 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4756 ByteValues);
4757 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004758 }
4759
Chris Lattner8c34cd22008-10-05 02:13:19 +00004760 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4761 // the input value to the bswap. Some observations: 1) if more than one byte
4762 // is demanded from this input, then it could not be successfully assembled
4763 // into a byteswap. At least one of the two bytes would not be aligned with
4764 // their ultimate destination.
4765 if (!isPowerOf2_32(ByteMask)) return true;
4766 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004767
Chris Lattner8c34cd22008-10-05 02:13:19 +00004768 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4769 // is demanded, it needs to go into byte 0 of the result. This means that the
4770 // byte needs to be shifted until it lands in the right byte bucket. The
4771 // shift amount depends on the position: if the byte is coming from the high
4772 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4773 // low part, it must be shifted left.
4774 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4775 if (InputByteNo < ByteValues.size()/2) {
4776 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4777 return true;
4778 } else {
4779 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4780 return true;
4781 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004782
4783 // If the destination byte value is already defined, the values are or'd
4784 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004785 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004786 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004787 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004788 return false;
4789}
4790
4791/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4792/// If so, insert the new bswap intrinsic and return it.
4793Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004794 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004795 if (!ITy || ITy->getBitWidth() % 16 ||
4796 // ByteMask only allows up to 32-byte values.
4797 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004798 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004799
4800 /// ByteValues - For each byte of the result, we keep track of which value
4801 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004802 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004803 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004804
4805 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004806 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4807 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004808 return 0;
4809
4810 // Check to see if all of the bytes come from the same value.
4811 Value *V = ByteValues[0];
4812 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4813
4814 // Check to make sure that all of the bytes come from the same value.
4815 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4816 if (ByteValues[i] != V)
4817 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004818 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004819 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004820 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004821 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004822}
4823
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004824/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4825/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4826/// we can simplify this expression to "cond ? C : D or B".
4827static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004828 Value *C, Value *D,
4829 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004830 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004831 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004832 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004833 return 0;
4834
Chris Lattnera6a474d2008-11-16 04:26:55 +00004835 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004836 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004837 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004838 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004839 return SelectInst::Create(Cond, C, B);
4840 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004842 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004843 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004844 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004845 return 0;
4846}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004847
Chris Lattner69d4ced2008-11-16 05:20:07 +00004848/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4849Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4850 ICmpInst *LHS, ICmpInst *RHS) {
4851 Value *Val, *Val2;
4852 ConstantInt *LHSCst, *RHSCst;
4853 ICmpInst::Predicate LHSCC, RHSCC;
4854
4855 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004856 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4857 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004858 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004859
4860
4861 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4862 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4863 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4864 Value *NewOr = Builder->CreateOr(Val, Val2);
4865 return new ICmpInst(LHSCC, NewOr, LHSCst);
4866 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004867
4868 // From here on, we only handle:
4869 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4870 if (Val != Val2) return 0;
4871
4872 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4873 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4874 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4875 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4876 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4877 return 0;
4878
4879 // We can't fold (ugt x, C) | (sgt x, C2).
4880 if (!PredicatesFoldable(LHSCC, RHSCC))
4881 return 0;
4882
4883 // Ensure that the larger constant is on the RHS.
4884 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004885 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004886 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004887 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004888 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4889 else
4890 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4891
4892 if (ShouldSwap) {
4893 std::swap(LHS, RHS);
4894 std::swap(LHSCst, RHSCst);
4895 std::swap(LHSCC, RHSCC);
4896 }
4897
4898 // At this point, we know we have have two icmp instructions
4899 // comparing a value against two constants and or'ing the result
4900 // together. Because of the above check, we know that we only have
4901 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4902 // FoldICmpLogical check above), that the two constants are not
4903 // equal.
4904 assert(LHSCst != RHSCst && "Compares not folded above?");
4905
4906 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004908 case ICmpInst::ICMP_EQ:
4909 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004910 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004911 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004912 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004913 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004914 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004915 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004916 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004917 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004918 }
4919 break; // (X == 13 | X == 15) -> no change
4920 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4921 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4922 break;
4923 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4924 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4925 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4926 return ReplaceInstUsesWith(I, RHS);
4927 }
4928 break;
4929 case ICmpInst::ICMP_NE:
4930 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004931 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004932 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4933 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4934 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4935 return ReplaceInstUsesWith(I, LHS);
4936 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4937 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4938 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004939 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004940 }
4941 break;
4942 case ICmpInst::ICMP_ULT:
4943 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004944 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004945 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4946 break;
4947 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4948 // If RHSCst is [us]MAXINT, it is always false. Not handling
4949 // this can cause overflow.
4950 if (RHSCst->isMaxValue(false))
4951 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004952 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004953 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004954 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4955 break;
4956 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4957 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4958 return ReplaceInstUsesWith(I, RHS);
4959 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4960 break;
4961 }
4962 break;
4963 case ICmpInst::ICMP_SLT:
4964 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004965 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004966 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4967 break;
4968 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4969 // If RHSCst is [us]MAXINT, it is always false. Not handling
4970 // this can cause overflow.
4971 if (RHSCst->isMaxValue(true))
4972 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004973 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004974 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004975 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4976 break;
4977 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4978 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4979 return ReplaceInstUsesWith(I, RHS);
4980 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4981 break;
4982 }
4983 break;
4984 case ICmpInst::ICMP_UGT:
4985 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004986 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004987 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4988 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4989 return ReplaceInstUsesWith(I, LHS);
4990 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4991 break;
4992 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4993 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004994 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004995 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4996 break;
4997 }
4998 break;
4999 case ICmpInst::ICMP_SGT:
5000 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005001 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00005002 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
5003 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
5004 return ReplaceInstUsesWith(I, LHS);
5005 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
5006 break;
5007 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
5008 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005009 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00005010 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
5011 break;
5012 }
5013 break;
5014 }
5015 return 0;
5016}
5017
Chris Lattner5414cc52009-07-23 05:46:22 +00005018Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
5019 FCmpInst *RHS) {
5020 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
5021 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
5022 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
5023 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
5024 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
5025 // If either of the constants are nans, then the whole thing returns
5026 // true.
5027 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00005028 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005029
5030 // Otherwise, no need to compare the two constants, compare the
5031 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005032 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005033 LHS->getOperand(0), RHS->getOperand(0));
5034 }
5035
5036 // Handle vector zeros. This occurs because the canonical form of
5037 // "fcmp uno x,x" is "fcmp uno x, 0".
5038 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
5039 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005040 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00005041 LHS->getOperand(0), RHS->getOperand(0));
5042
5043 return 0;
5044 }
5045
5046 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
5047 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
5048 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
5049
5050 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
5051 // Swap RHS operands to match LHS.
5052 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
5053 std::swap(Op1LHS, Op1RHS);
5054 }
5055 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
5056 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
5057 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005058 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00005059 Op0LHS, Op0RHS);
5060 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005061 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00005062 if (Op0CC == FCmpInst::FCMP_FALSE)
5063 return ReplaceInstUsesWith(I, RHS);
5064 if (Op1CC == FCmpInst::FCMP_FALSE)
5065 return ReplaceInstUsesWith(I, LHS);
5066 bool Op0Ordered;
5067 bool Op1Ordered;
5068 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
5069 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
5070 if (Op0Ordered == Op1Ordered) {
5071 // If both are ordered or unordered, return a new fcmp with
5072 // or'ed predicates.
5073 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
5074 Op0LHS, Op0RHS, Context);
5075 if (Instruction *I = dyn_cast<Instruction>(RV))
5076 return I;
5077 // Otherwise, it's a constant boolean value...
5078 return ReplaceInstUsesWith(I, RV);
5079 }
5080 }
5081 return 0;
5082}
5083
Bill Wendlinga698a472008-12-01 08:23:25 +00005084/// FoldOrWithConstants - This helper function folds:
5085///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005086/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005087///
5088/// into:
5089///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005090/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005091///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005092/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005093Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005094 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005095 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5096 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005097
Bill Wendling286a0542008-12-02 06:24:20 +00005098 Value *V1 = 0;
5099 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005100 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005101
Bill Wendling29976b92008-12-02 06:18:11 +00005102 APInt Xor = CI1->getValue() ^ CI2->getValue();
5103 if (!Xor.isAllOnesValue()) return 0;
5104
Bill Wendling286a0542008-12-02 06:24:20 +00005105 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005106 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005107 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005108 }
5109
5110 return 0;
5111}
5112
Chris Lattner7e708292002-06-25 16:13:24 +00005113Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005114 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005115 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005116
Chris Lattnerd06094f2009-11-10 00:55:12 +00005117 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5118 return ReplaceInstUsesWith(I, V);
5119
5120
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005121 // See if we can simplify any instructions used by the instruction whose sole
5122 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005123 if (SimplifyDemandedInstructionBits(I))
5124 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005125
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005126 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005127 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005128 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005129 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005130 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005131 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005132 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005133 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005134 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005135 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005136
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005137 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005138 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005139 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005140 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005141 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005142 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005143 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005144 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005145
5146 // Try to fold constant and into select arguments.
5147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005149 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005150 if (isa<PHINode>(Op0))
5151 if (Instruction *NV = FoldOpIntoPhi(I))
5152 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005153 }
5154
Chris Lattner4f637d42006-01-06 17:59:59 +00005155 Value *A = 0, *B = 0;
5156 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005157
Chris Lattner6423d4c2006-07-10 20:25:24 +00005158 // (A | B) | C and A | (B | C) -> bswap if possible.
5159 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005160 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5161 match(Op1, m_Or(m_Value(), m_Value())) ||
5162 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5163 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005164 if (Instruction *BSwap = MatchBSwap(I))
5165 return BSwap;
5166 }
5167
Chris Lattner6e4c6492005-05-09 04:58:36 +00005168 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005169 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005170 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005171 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005172 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005173 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005175 }
5176
5177 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005178 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005180 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005181 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005182 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005183 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005184 }
5185
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005186 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005187 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5189 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005190 Value *V1 = 0, *V2 = 0, *V3 = 0;
5191 C1 = dyn_cast<ConstantInt>(C);
5192 C2 = dyn_cast<ConstantInt>(D);
5193 if (C1 && C2) { // (A & C1)|(B & C2)
5194 // If we have: ((V + N) & C1) | (V & C2)
5195 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5196 // replace with V+N.
5197 if (C1->getValue() == ~C2->getValue()) {
5198 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005199 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005200 // Add commutes, try both ways.
5201 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5202 return ReplaceInstUsesWith(I, A);
5203 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5204 return ReplaceInstUsesWith(I, A);
5205 }
5206 // Or commutes, try both ways.
5207 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005208 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005209 // Add commutes, try both ways.
5210 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5211 return ReplaceInstUsesWith(I, B);
5212 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5213 return ReplaceInstUsesWith(I, B);
5214 }
5215 }
Chris Lattner044e5332007-04-08 08:01:49 +00005216 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00005217 }
5218
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005219 // Check to see if we have any common things being and'ed. If so, find the
5220 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005221 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
5222 if (A == B) // (A & C)|(A & D) == A & (C|D)
5223 V1 = A, V2 = C, V3 = D;
5224 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5225 V1 = A, V2 = B, V3 = C;
5226 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5227 V1 = C, V2 = A, V3 = D;
5228 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5229 V1 = C, V2 = A, V3 = B;
5230
5231 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005232 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005233 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005234 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005235 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005236
Dan Gohman1975d032008-10-30 20:40:10 +00005237 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005238 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005239 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005240 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005241 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005242 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005243 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005244 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005245 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005246
Bill Wendlingb01865c2008-11-30 13:52:49 +00005247 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005248 if ((match(C, m_Not(m_Specific(D))) &&
5249 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005250 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005251 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005252 if ((match(A, m_Not(m_Specific(D))) &&
5253 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005254 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005255 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005256 if ((match(C, m_Not(m_Specific(B))) &&
5257 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005258 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005259 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005260 if ((match(A, m_Not(m_Specific(B))) &&
5261 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005262 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005263 }
Chris Lattnere511b742006-11-14 07:46:50 +00005264
5265 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005266 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5267 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5268 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005269 SI0->getOperand(1) == SI1->getOperand(1) &&
5270 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005271 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5272 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005273 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005274 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005275 }
5276 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005277
Bill Wendlingb3833d12008-12-01 01:07:11 +00005278 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005279 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5280 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005281 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005282 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005283 }
5284 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005285 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5286 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005287 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005288 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005289 }
5290
Chris Lattnerd06094f2009-11-10 00:55:12 +00005291 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5292 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5293 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5294 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5295 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5296 I.getName()+".demorgan");
5297 return BinaryOperator::CreateNot(And);
5298 }
Chris Lattnera2881962003-02-18 19:28:33 +00005299
Reid Spencere4d87aa2006-12-23 06:05:41 +00005300 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5301 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005302 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005303 return R;
5304
Chris Lattner69d4ced2008-11-16 05:20:07 +00005305 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5306 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5307 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005308 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005309
5310 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005311 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005312 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005313 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005314 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5315 !isa<ICmpInst>(Op1C->getOperand(0))) {
5316 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005317 if (SrcTy == Op1C->getOperand(0)->getType() &&
5318 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005319 // Only do this if the casts both really cause code to be
5320 // generated.
5321 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5322 I.getType(), TD) &&
5323 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5324 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005325 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5326 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005327 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005328 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005329 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005330 }
Chris Lattner99c65742007-10-24 05:38:08 +00005331 }
5332
5333
5334 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5335 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005336 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5337 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5338 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005339 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005340
Chris Lattner7e708292002-06-25 16:13:24 +00005341 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005342}
5343
Dan Gohman844731a2008-05-13 00:00:25 +00005344namespace {
5345
Chris Lattnerc317d392004-02-16 01:20:27 +00005346// XorSelf - Implements: X ^ X --> 0
5347struct XorSelf {
5348 Value *RHS;
5349 XorSelf(Value *rhs) : RHS(rhs) {}
5350 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5351 Instruction *apply(BinaryOperator &Xor) const {
5352 return &Xor;
5353 }
5354};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005355
Dan Gohman844731a2008-05-13 00:00:25 +00005356}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005357
Chris Lattner7e708292002-06-25 16:13:24 +00005358Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005359 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005360 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005361
Evan Chengd34af782008-03-25 20:07:13 +00005362 if (isa<UndefValue>(Op1)) {
5363 if (isa<UndefValue>(Op0))
5364 // Handle undef ^ undef -> 0 special case. This is a common
5365 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005367 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005368 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005369
Chris Lattnerc317d392004-02-16 01:20:27 +00005370 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005371 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005372 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005374 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005375
5376 // See if we can simplify any instructions used by the instruction whose sole
5377 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005378 if (SimplifyDemandedInstructionBits(I))
5379 return &I;
5380 if (isa<VectorType>(I.getType()))
5381 if (isa<ConstantAggregateZero>(Op1))
5382 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005383
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005384 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005385 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005386 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5387 if (Op0I->getOpcode() == Instruction::And ||
5388 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005389 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5390 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5391 if (dyn_castNotVal(Op0I->getOperand(1)))
5392 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005393 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005394 Value *NotY =
5395 Builder->CreateNot(Op0I->getOperand(1),
5396 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005397 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005398 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005399 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005400 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005401
5402 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5403 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5404 if (isFreeToInvert(Op0I->getOperand(0)) &&
5405 isFreeToInvert(Op0I->getOperand(1))) {
5406 Value *NotX =
5407 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5408 Value *NotY =
5409 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5410 if (Op0I->getOpcode() == Instruction::And)
5411 return BinaryOperator::CreateOr(NotX, NotY);
5412 return BinaryOperator::CreateAnd(NotX, NotY);
5413 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005414 }
5415 }
5416 }
5417
5418
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005419 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005420 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005421 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005422 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005423 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005424 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005425
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005426 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005427 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005428 FCI->getOperand(0), FCI->getOperand(1));
5429 }
5430
Nick Lewycky517e1f52008-05-31 19:01:33 +00005431 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5432 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5433 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5434 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5435 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005436 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5437 (RHS == ConstantExpr::getCast(Opcode,
5438 ConstantInt::getTrue(*Context),
5439 Op0C->getDestTy()))) {
5440 CI->setPredicate(CI->getInversePredicate());
5441 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005442 }
5443 }
5444 }
5445 }
5446
Reid Spencere4d87aa2006-12-23 06:05:41 +00005447 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005448 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005449 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5450 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005451 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5452 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005453 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005454 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005455 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005456
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005457 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005458 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005459 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005460 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005461 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005462 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005463 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005464 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005465 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005466 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005467 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005468 Constant *C = ConstantInt::get(*Context,
5469 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005470 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005471
Chris Lattner7c4049c2004-01-12 19:35:11 +00005472 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005473 } else if (Op0I->getOpcode() == Instruction::Or) {
5474 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005475 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005476 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005477 // Anything in both C1 and C2 is known to be zero, remove it from
5478 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005479 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5480 NewRHS = ConstantExpr::getAnd(NewRHS,
5481 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005482 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005483 I.setOperand(0, Op0I->getOperand(0));
5484 I.setOperand(1, NewRHS);
5485 return &I;
5486 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005487 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005488 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005489 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005490
5491 // Try to fold constant and into select arguments.
5492 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005493 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005494 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005495 if (isa<PHINode>(Op0))
5496 if (Instruction *NV = FoldOpIntoPhi(I))
5497 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005498 }
5499
Dan Gohman186a6362009-08-12 16:04:34 +00005500 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005501 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005502 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005503
Dan Gohman186a6362009-08-12 16:04:34 +00005504 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005505 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005506 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005507
Chris Lattner318bf792007-03-18 22:51:34 +00005508
5509 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5510 if (Op1I) {
5511 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005512 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005513 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005514 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005515 I.swapOperands();
5516 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005517 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005518 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005519 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005520 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005521 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005522 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005523 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005524 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005525 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005526 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005527 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005528 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005529 std::swap(A, B);
5530 }
Chris Lattner318bf792007-03-18 22:51:34 +00005531 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005532 I.swapOperands(); // Simplified below.
5533 std::swap(Op0, Op1);
5534 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005535 }
Chris Lattner318bf792007-03-18 22:51:34 +00005536 }
5537
5538 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5539 if (Op0I) {
5540 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005541 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005542 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005543 if (A == Op1) // (B|A)^B == (A|B)^B
5544 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005545 if (B == Op1) // (A|B)^B == A & ~B
5546 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005547 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005548 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005549 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005550 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005551 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005552 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005553 if (A == Op1) // (A&B)^A -> (B&A)^A
5554 std::swap(A, B);
5555 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005556 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005557 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005558 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005559 }
Chris Lattner318bf792007-03-18 22:51:34 +00005560 }
5561
5562 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5563 if (Op0I && Op1I && Op0I->isShift() &&
5564 Op0I->getOpcode() == Op1I->getOpcode() &&
5565 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5566 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005567 Value *NewOp =
5568 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5569 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005570 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005571 Op1I->getOperand(1));
5572 }
5573
5574 if (Op0I && Op1I) {
5575 Value *A, *B, *C, *D;
5576 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005577 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5578 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005579 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005580 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005581 }
5582 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005583 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5584 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005585 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005586 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005587 }
5588
5589 // (A & B)^(C & D)
5590 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005591 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5592 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005593 // (X & Y)^(X & Y) -> (Y^Z) & X
5594 Value *X = 0, *Y = 0, *Z = 0;
5595 if (A == C)
5596 X = A, Y = B, Z = D;
5597 else if (A == D)
5598 X = A, Y = B, Z = C;
5599 else if (B == C)
5600 X = B, Y = A, Z = D;
5601 else if (B == D)
5602 X = B, Y = A, Z = C;
5603
5604 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005605 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005606 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005607 }
5608 }
5609 }
5610
Reid Spencere4d87aa2006-12-23 06:05:41 +00005611 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5612 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005613 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005614 return R;
5615
Chris Lattner6fc205f2006-05-05 06:39:07 +00005616 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005617 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005618 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005619 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5620 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005621 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005622 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005623 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5624 I.getType(), TD) &&
5625 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5626 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005627 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5628 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005629 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005630 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005631 }
Chris Lattner99c65742007-10-24 05:38:08 +00005632 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005633
Chris Lattner7e708292002-06-25 16:13:24 +00005634 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005635}
5636
Owen Andersond672ecb2009-07-03 00:17:18 +00005637static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005638 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005639 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005640}
Chris Lattnera96879a2004-09-29 17:40:11 +00005641
Dan Gohman6de29f82009-06-15 22:12:54 +00005642static bool HasAddOverflow(ConstantInt *Result,
5643 ConstantInt *In1, ConstantInt *In2,
5644 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005645 if (IsSigned)
5646 if (In2->getValue().isNegative())
5647 return Result->getValue().sgt(In1->getValue());
5648 else
5649 return Result->getValue().slt(In1->getValue());
5650 else
5651 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005652}
5653
Dan Gohman6de29f82009-06-15 22:12:54 +00005654/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005655/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005656static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005657 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005658 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005659 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005660
Dan Gohman6de29f82009-06-15 22:12:54 +00005661 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5662 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005663 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005664 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5665 ExtractElement(In1, Idx, Context),
5666 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005667 IsSigned))
5668 return true;
5669 }
5670 return false;
5671 }
5672
5673 return HasAddOverflow(cast<ConstantInt>(Result),
5674 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5675 IsSigned);
5676}
5677
5678static bool HasSubOverflow(ConstantInt *Result,
5679 ConstantInt *In1, ConstantInt *In2,
5680 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005681 if (IsSigned)
5682 if (In2->getValue().isNegative())
5683 return Result->getValue().slt(In1->getValue());
5684 else
5685 return Result->getValue().sgt(In1->getValue());
5686 else
5687 return Result->getValue().ugt(In1->getValue());
5688}
5689
Dan Gohman6de29f82009-06-15 22:12:54 +00005690/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5691/// overflowed for this type.
5692static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005693 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005694 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005695 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005696
5697 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5698 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005699 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005700 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5701 ExtractElement(In1, Idx, Context),
5702 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005703 IsSigned))
5704 return true;
5705 }
5706 return false;
5707 }
5708
5709 return HasSubOverflow(cast<ConstantInt>(Result),
5710 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5711 IsSigned);
5712}
5713
Chris Lattner10c0d912008-04-22 02:53:33 +00005714
Reid Spencere4d87aa2006-12-23 06:05:41 +00005715/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005716/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005717Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005718 ICmpInst::Predicate Cond,
5719 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005720 // Look through bitcasts.
5721 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5722 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005723
Chris Lattner574da9b2005-01-13 20:14:25 +00005724 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005725 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005726 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005727 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005728 // know pointers can't overflow since the gep is inbounds. See if we can
5729 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005730 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5731
5732 // If not, synthesize the offset the hard way.
5733 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005734 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005735 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005736 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005737 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005738 // If the base pointers are different, but the indices are the same, just
5739 // compare the base pointer.
5740 if (PtrBase != GEPRHS->getOperand(0)) {
5741 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005742 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005743 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005744 if (IndicesTheSame)
5745 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5746 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5747 IndicesTheSame = false;
5748 break;
5749 }
5750
5751 // If all indices are the same, just compare the base pointers.
5752 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005753 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005754 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005755
5756 // Otherwise, the base pointers are different and the indices are
5757 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005758 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005759 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005760
Chris Lattnere9d782b2005-01-13 22:25:21 +00005761 // If one of the GEPs has all zero indices, recurse.
5762 bool AllZeros = true;
5763 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5764 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5765 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5766 AllZeros = false;
5767 break;
5768 }
5769 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005770 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5771 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005772
5773 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005774 AllZeros = true;
5775 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5776 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5777 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5778 AllZeros = false;
5779 break;
5780 }
5781 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005782 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005783
Chris Lattner4401c9c2005-01-14 00:20:05 +00005784 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5785 // If the GEPs only differ by one index, compare it.
5786 unsigned NumDifferences = 0; // Keep track of # differences.
5787 unsigned DiffOperand = 0; // The operand that differs.
5788 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5789 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005790 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5791 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005792 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005793 NumDifferences = 2;
5794 break;
5795 } else {
5796 if (NumDifferences++) break;
5797 DiffOperand = i;
5798 }
5799 }
5800
5801 if (NumDifferences == 0) // SAME GEP?
5802 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005803 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005804 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005805
Chris Lattner4401c9c2005-01-14 00:20:05 +00005806 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005807 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5808 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005809 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005810 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005811 }
5812 }
5813
Reid Spencere4d87aa2006-12-23 06:05:41 +00005814 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005815 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005816 if (TD &&
5817 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005818 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5819 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005820 Value *L = EmitGEPOffset(GEPLHS, *this);
5821 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005822 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005823 }
5824 }
5825 return 0;
5826}
5827
Chris Lattnera5406232008-05-19 20:18:56 +00005828/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5829///
5830Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5831 Instruction *LHSI,
5832 Constant *RHSC) {
5833 if (!isa<ConstantFP>(RHSC)) return 0;
5834 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5835
5836 // Get the width of the mantissa. We don't want to hack on conversions that
5837 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005838 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005839 if (MantissaWidth == -1) return 0; // Unknown.
5840
5841 // Check to see that the input is converted from an integer type that is small
5842 // enough that preserves all bits. TODO: check here for "known" sign bits.
5843 // 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 +00005844 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005845
5846 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005847 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5848 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005849 ++InputSize;
5850
5851 // If the conversion would lose info, don't hack on this.
5852 if ((int)InputSize > MantissaWidth)
5853 return 0;
5854
5855 // Otherwise, we can potentially simplify the comparison. We know that it
5856 // will always come through as an integer value and we know the constant is
5857 // not a NAN (it would have been previously simplified).
5858 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5859
5860 ICmpInst::Predicate Pred;
5861 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005862 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005863 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005864 case FCmpInst::FCMP_OEQ:
5865 Pred = ICmpInst::ICMP_EQ;
5866 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005867 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005868 case FCmpInst::FCMP_OGT:
5869 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5870 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005871 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005872 case FCmpInst::FCMP_OGE:
5873 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5874 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005875 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005876 case FCmpInst::FCMP_OLT:
5877 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5878 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005879 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005880 case FCmpInst::FCMP_OLE:
5881 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5882 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005883 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005884 case FCmpInst::FCMP_ONE:
5885 Pred = ICmpInst::ICMP_NE;
5886 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005887 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005888 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005889 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005890 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005891 }
5892
5893 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5894
5895 // Now we know that the APFloat is a normal number, zero or inf.
5896
Chris Lattner85162782008-05-20 03:50:52 +00005897 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005898 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005899 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005900
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005901 if (!LHSUnsigned) {
5902 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5903 // and large values.
5904 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5905 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5906 APFloat::rmNearestTiesToEven);
5907 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5908 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5909 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005910 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5911 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005912 }
5913 } else {
5914 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5915 // +INF and large values.
5916 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5917 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5918 APFloat::rmNearestTiesToEven);
5919 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5920 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5921 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005922 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5923 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005924 }
Chris Lattnera5406232008-05-19 20:18:56 +00005925 }
5926
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005927 if (!LHSUnsigned) {
5928 // See if the RHS value is < SignedMin.
5929 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5930 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5931 APFloat::rmNearestTiesToEven);
5932 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5933 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5934 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005935 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5936 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005937 }
Chris Lattnera5406232008-05-19 20:18:56 +00005938 }
5939
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005940 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5941 // [0, UMAX], but it may still be fractional. See if it is fractional by
5942 // casting the FP value to the integer value and back, checking for equality.
5943 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005944 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005945 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5946 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005947 if (!RHS.isZero()) {
5948 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005949 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5950 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005951 if (!Equal) {
5952 // If we had a comparison against a fractional value, we have to adjust
5953 // the compare predicate and sometimes the value. RHSC is rounded towards
5954 // zero at this point.
5955 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005956 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005957 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005958 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005959 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005960 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005961 case ICmpInst::ICMP_ULE:
5962 // (float)int <= 4.4 --> int <= 4
5963 // (float)int <= -4.4 --> false
5964 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005965 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005966 break;
5967 case ICmpInst::ICMP_SLE:
5968 // (float)int <= 4.4 --> int <= 4
5969 // (float)int <= -4.4 --> int < -4
5970 if (RHS.isNegative())
5971 Pred = ICmpInst::ICMP_SLT;
5972 break;
5973 case ICmpInst::ICMP_ULT:
5974 // (float)int < -4.4 --> false
5975 // (float)int < 4.4 --> int <= 4
5976 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005977 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005978 Pred = ICmpInst::ICMP_ULE;
5979 break;
5980 case ICmpInst::ICMP_SLT:
5981 // (float)int < -4.4 --> int < -4
5982 // (float)int < 4.4 --> int <= 4
5983 if (!RHS.isNegative())
5984 Pred = ICmpInst::ICMP_SLE;
5985 break;
5986 case ICmpInst::ICMP_UGT:
5987 // (float)int > 4.4 --> int > 4
5988 // (float)int > -4.4 --> true
5989 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005990 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005991 break;
5992 case ICmpInst::ICMP_SGT:
5993 // (float)int > 4.4 --> int > 4
5994 // (float)int > -4.4 --> int >= -4
5995 if (RHS.isNegative())
5996 Pred = ICmpInst::ICMP_SGE;
5997 break;
5998 case ICmpInst::ICMP_UGE:
5999 // (float)int >= -4.4 --> true
6000 // (float)int >= 4.4 --> int > 4
6001 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00006002 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00006003 Pred = ICmpInst::ICMP_UGT;
6004 break;
6005 case ICmpInst::ICMP_SGE:
6006 // (float)int >= -4.4 --> int >= -4
6007 // (float)int >= 4.4 --> int > 4
6008 if (!RHS.isNegative())
6009 Pred = ICmpInst::ICMP_SGT;
6010 break;
6011 }
Chris Lattnera5406232008-05-19 20:18:56 +00006012 }
6013 }
6014
6015 // Lower this FP comparison into an appropriate integer version of the
6016 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006017 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00006018}
6019
Chris Lattner1f12e442010-01-02 08:12:04 +00006020
6021/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
6022/// cmp pred (load (gep GV, ...)), cmpcst
6023/// where GV is a global variable with a constant initializer. Try to simplify
Chris Lattner82602bc2010-01-02 20:20:33 +00006024/// this into some simple computation that does not need the load. For example
6025/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006026///
6027/// If AndCst is non-null, then the loaded value is masked with that constant
6028/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Chris Lattner1f12e442010-01-02 08:12:04 +00006029Instruction *InstCombiner::
6030FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006031 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006032
6033 // There are many forms of this optimization we can handle, for now, just do
6034 // the simple index into a single-dimensional array.
6035 //
6036 // Require: GEP GV, 0, i
6037 if (GEP->getNumOperands() != 3 ||
6038 !isa<ConstantInt>(GEP->getOperand(1)) ||
6039 !cast<ConstantInt>(GEP->getOperand(1))->isZero())
6040 return 0;
6041
6042 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
6043 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
6044
Chris Lattner82602bc2010-01-02 20:20:33 +00006045 enum { Overdefined = -3, Undefined = -2 };
6046
Chris Lattner1f12e442010-01-02 08:12:04 +00006047 // Variables for our state machines.
6048
Chris Lattnerbef37372010-01-02 09:35:17 +00006049 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6050 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
Chris Lattner82602bc2010-01-02 20:20:33 +00006051 // and 87 is the second (and last) index. FirstTrueElement is -2 when
Chris Lattnerbef37372010-01-02 09:35:17 +00006052 // undefined, otherwise set to the first true element. SecondTrueElement is
Chris Lattner82602bc2010-01-02 20:20:33 +00006053 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
6054 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006055
Chris Lattnerbef37372010-01-02 09:35:17 +00006056 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6057 // form "i != 47 & i != 87". Same state transitions as for true elements.
Chris Lattner82602bc2010-01-02 20:20:33 +00006058 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006059
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006060 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
6061 /// define a state machine that triggers for ranges of values that the index
6062 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
6063 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
6064 /// index in the range (inclusive). We use -2 for undefined here because we
6065 /// use relative comparisons and don't want 0-1 to match -1.
6066 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
6067
Chris Lattner10d514e2010-01-02 08:56:52 +00006068 // MagicBitvector - This is a magic bitvector where we set a bit if the
6069 // comparison is true for element 'i'. If there are 64 elements or less in
6070 // the array, this will fully represent all the comparison results.
6071 uint64_t MagicBitvector = 0;
6072
6073
Chris Lattner1f12e442010-01-02 08:12:04 +00006074 // Scan the array and see if one of our patterns matches.
6075 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6076 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006077 Constant *Elt = Init->getOperand(i);
6078
6079 // If the element is masked, handle it.
6080 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
6081
Chris Lattner1f12e442010-01-02 08:12:04 +00006082 // Find out if the comparison would be true or false for the i'th element.
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006083 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chris Lattner1f12e442010-01-02 08:12:04 +00006084 CompareRHS, TD);
6085 // If the result is undef for this element, ignore it.
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006086 if (isa<UndefValue>(C)) {
6087 // Extend range state machines to cover this element in case there is an
6088 // undef in the middle of the range.
6089 if (TrueRangeEnd == (int)i-1)
6090 TrueRangeEnd = i;
6091 if (FalseRangeEnd == (int)i-1)
6092 FalseRangeEnd = i;
6093 continue;
6094 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006095
6096 // If we can't compute the result for any of the elements, we have to give
6097 // up evaluating the entire conditional.
6098 if (!isa<ConstantInt>(C)) return 0;
6099
6100 // Otherwise, we know if the comparison is true or false for this element,
6101 // update our state machines.
6102 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6103
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006104 // State machine for single/double/range index comparison.
Chris Lattner1f12e442010-01-02 08:12:04 +00006105 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00006106 // Update the TrueElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006107 if (FirstTrueElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006108 FirstTrueElement = TrueRangeEnd = i; // First true element.
6109 else {
6110 // Update double-compare state machine.
6111 if (SecondTrueElement == Undefined)
6112 SecondTrueElement = i;
6113 else
6114 SecondTrueElement = Overdefined;
6115
6116 // Update range state machine.
6117 if (TrueRangeEnd == (int)i-1)
6118 TrueRangeEnd = i;
6119 else
6120 TrueRangeEnd = Overdefined;
6121 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006122 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00006123 // Update the FalseElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006124 if (FirstFalseElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006125 FirstFalseElement = FalseRangeEnd = i; // First false element.
6126 else {
6127 // Update double-compare state machine.
6128 if (SecondFalseElement == Undefined)
6129 SecondFalseElement = i;
6130 else
6131 SecondFalseElement = Overdefined;
6132
6133 // Update range state machine.
6134 if (FalseRangeEnd == (int)i-1)
6135 FalseRangeEnd = i;
6136 else
6137 FalseRangeEnd = Overdefined;
6138 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006139 }
6140
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006141
Chris Lattner10d514e2010-01-02 08:56:52 +00006142 // If this element is in range, update our magic bitvector.
6143 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00006144 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00006145
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006146 // If all of our states become overdefined, bail out early. Since the
6147 // predicate is expensive, only check it every 8 elements. This is only
6148 // really useful for really huge arrays.
6149 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
6150 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
6151 FalseRangeEnd == Overdefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006152 return 0;
6153 }
6154
6155 // Now that we've scanned the entire array, emit our new comparison(s). We
6156 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00006157 Value *Idx = GEP->getOperand(2);
6158
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006159
Chris Lattnerbef37372010-01-02 09:35:17 +00006160 // If the comparison is only true for one or two elements, emit direct
6161 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006162 if (SecondTrueElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006163 // None true -> false.
Chris Lattner82602bc2010-01-02 20:20:33 +00006164 if (FirstTrueElement == Undefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006165 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6166
Chris Lattnerbef37372010-01-02 09:35:17 +00006167 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6168
Chris Lattner1f12e442010-01-02 08:12:04 +00006169 // True for one element -> 'i == 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006170 if (SecondTrueElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006171 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6172
6173 // True for two elements -> 'i == 47 | i == 72'.
6174 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6175 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6176 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6177 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006178 }
6179
Chris Lattnerbef37372010-01-02 09:35:17 +00006180 // If the comparison is only false for one or two elements, emit direct
6181 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006182 if (SecondFalseElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006183 // None false -> true.
Chris Lattner82602bc2010-01-02 20:20:33 +00006184 if (FirstFalseElement == Undefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006185 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6186
Chris Lattnerbef37372010-01-02 09:35:17 +00006187 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6188
6189 // False for one element -> 'i != 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006190 if (SecondFalseElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006191 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6192
6193 // False for two elements -> 'i != 47 & i != 72'.
6194 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6195 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6196 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6197 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006198 }
6199
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006200 // If the comparison can be replaced with a range comparison for the elements
6201 // where it is true, emit the range check.
6202 if (TrueRangeEnd != Overdefined) {
6203 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
6204
6205 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
6206 if (FirstTrueElement) {
6207 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
6208 Idx = Builder->CreateAdd(Idx, Offs);
6209 }
6210
6211 Value *End = ConstantInt::get(Idx->getType(),
6212 TrueRangeEnd-FirstTrueElement+1);
6213 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
6214 }
6215
6216 // False range check.
6217 if (FalseRangeEnd != Overdefined) {
6218 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
6219 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
6220 if (FirstFalseElement) {
6221 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
6222 Idx = Builder->CreateAdd(Idx, Offs);
6223 }
6224
6225 Value *End = ConstantInt::get(Idx->getType(),
6226 FalseRangeEnd-FirstFalseElement);
6227 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
6228 }
6229
6230
Chris Lattner10d514e2010-01-02 08:56:52 +00006231 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6232 // of this load, replace it with computation that does:
6233 // ((magic_cst >> i) & 1) != 0
6234 if (Init->getNumOperands() <= 32 ||
6235 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6236 const Type *Ty;
6237 if (Init->getNumOperands() <= 32)
6238 Ty = Type::getInt32Ty(Init->getContext());
6239 else
6240 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00006241 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00006242 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6243 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6244 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6245 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006246
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006247 // TODO: GEP 0, i, 4
Chris Lattner5fadf172010-01-02 20:07:03 +00006248
Chris Lattner1f12e442010-01-02 08:12:04 +00006249 return 0;
6250}
6251
6252
Reid Spencere4d87aa2006-12-23 06:05:41 +00006253Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006254 bool Changed = false;
6255
6256 /// Orders the operands of the compare so that they are listed from most
6257 /// complex to least complex. This puts constants before unary operators,
6258 /// before binary operators.
6259 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6260 I.swapOperands();
6261 Changed = true;
6262 }
6263
Chris Lattner8b170942002-08-09 23:47:40 +00006264 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006265
Chris Lattner210c5d42009-11-09 23:55:12 +00006266 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6267 return ReplaceInstUsesWith(I, V);
6268
Chris Lattner58e97462007-01-14 19:42:17 +00006269 // Simplify 'fcmp pred X, X'
6270 if (Op0 == Op1) {
6271 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006272 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006273 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6274 case FCmpInst::FCMP_ULT: // True if unordered or less than
6275 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6276 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6277 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6278 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006279 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006280 return &I;
6281
6282 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6283 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6284 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6285 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6286 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6287 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006288 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006289 return &I;
6290 }
6291 }
6292
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // Handle fcmp with constant RHS
6294 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6295 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6296 switch (LHSI->getOpcode()) {
6297 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006298 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6299 // block. If in the same block, we're encouraging jump threading. If
6300 // not, we are just pessimizing the code by making an i1 phi.
6301 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006302 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006303 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006304 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006305 case Instruction::SIToFP:
6306 case Instruction::UIToFP:
6307 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6308 return NV;
6309 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00006310 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006311 // If either operand of the select is a constant, we can fold the
6312 // comparison into the select arms, which will cause one to be
6313 // constant folded and the select turned into a bitwise or.
6314 Value *Op1 = 0, *Op2 = 0;
6315 if (LHSI->hasOneUse()) {
6316 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6317 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006318 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006319 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006320 Op2 = Builder->CreateFCmp(I.getPredicate(),
6321 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006322 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6323 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006324 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006326 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6327 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006328 }
6329 }
6330
6331 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006332 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 break;
6334 }
Chris Lattner34e0c762010-01-02 08:20:51 +00006335 case Instruction::Load:
6336 if (GetElementPtrInst *GEP =
6337 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6338 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6339 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
6340 !cast<LoadInst>(LHSI)->isVolatile())
6341 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6342 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006343 //errs() << "NOT HANDLED FP: " << *GV << "\n";
Chris Lattner34e0c762010-01-02 08:20:51 +00006344 //errs() << "\t" << *GEP << "\n";
6345 //errs() << "\t " << I << "\n\n\n";
6346 }
6347 break;
6348 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006349 }
6350
6351 return Changed ? &I : 0;
6352}
6353
6354Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006355 bool Changed = false;
6356
6357 /// Orders the operands of the compare so that they are listed from most
6358 /// complex to least complex. This puts constants before unary operators,
6359 /// before binary operators.
6360 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6361 I.swapOperands();
6362 Changed = true;
6363 }
6364
Reid Spencere4d87aa2006-12-23 06:05:41 +00006365 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006366
Chris Lattner210c5d42009-11-09 23:55:12 +00006367 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6368 return ReplaceInstUsesWith(I, V);
6369
6370 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006371
Reid Spencere4d87aa2006-12-23 06:05:41 +00006372 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006373 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006374 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006375 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006376 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006377 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006378 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006379 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006380 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006381 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006382
Reid Spencere4d87aa2006-12-23 06:05:41 +00006383 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006384 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006385 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006386 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006387 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006388 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006389 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006390 case ICmpInst::ICMP_SGT:
6391 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006392 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006393 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006394 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006395 return BinaryOperator::CreateAnd(Not, Op0);
6396 }
6397 case ICmpInst::ICMP_UGE:
6398 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6399 // FALL THROUGH
6400 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006401 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006402 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006403 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006404 case ICmpInst::ICMP_SGE:
6405 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6406 // FALL THROUGH
6407 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006408 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006409 return BinaryOperator::CreateOr(Not, Op0);
6410 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006411 }
Chris Lattner8b170942002-08-09 23:47:40 +00006412 }
6413
Dan Gohman1c8491e2009-04-25 17:12:48 +00006414 unsigned BitWidth = 0;
6415 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006416 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6417 else if (Ty->isIntOrIntVector())
6418 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006419
6420 bool isSignBit = false;
6421
Dan Gohman81b28ce2008-09-16 18:46:06 +00006422 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006423 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006424 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006425
Chris Lattnerb6566012008-01-05 01:18:20 +00006426 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00006427 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006428 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006429 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006430 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006431 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006432
Dan Gohman81b28ce2008-09-16 18:46:06 +00006433 // If we have an icmp le or icmp ge instruction, turn it into the
6434 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006435 // them being folded in the code below. The SimplifyICmpInst code has
6436 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006437 switch (I.getPredicate()) {
6438 default: break;
6439 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006440 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006441 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006442 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006443 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006444 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006445 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006446 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006447 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006448 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006449 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006450 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006451 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006452 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006454 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006455 }
6456
Chris Lattner183661e2008-07-11 05:40:05 +00006457 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006458 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006459 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006460 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6461 }
6462
6463 // See if we can fold the comparison based on range information we can get
6464 // by checking whether bits are known to be zero or one in the input.
6465 if (BitWidth != 0) {
6466 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6467 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6468
6469 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006470 isSignBit ? APInt::getSignBit(BitWidth)
6471 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006472 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006473 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006474 if (SimplifyDemandedBits(I.getOperandUse(1),
6475 APInt::getAllOnesValue(BitWidth),
6476 Op1KnownZero, Op1KnownOne, 0))
6477 return &I;
6478
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006479 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006480 // in. Compute the Min, Max and RHS values based on the known bits. For the
6481 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006482 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6483 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006484 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006485 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6486 Op0Min, Op0Max);
6487 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6488 Op1Min, Op1Max);
6489 } else {
6490 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6491 Op0Min, Op0Max);
6492 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6493 Op1Min, Op1Max);
6494 }
6495
Chris Lattner183661e2008-07-11 05:40:05 +00006496 // If Min and Max are known to be the same, then SimplifyDemandedBits
6497 // figured out that the LHS is a constant. Just constant fold this now so
6498 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006499 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006500 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006501 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006502 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006503 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006504 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006505
Chris Lattner183661e2008-07-11 05:40:05 +00006506 // Based on the range information we know about the LHS, see if we can
6507 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006508 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006509 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006510 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006511 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006512 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006513 break;
6514 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006515 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006516 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006517 break;
6518 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006519 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006520 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006521 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006522 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006523 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006524 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006525 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6526 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006527 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006528 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006529
6530 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6531 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006532 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006533 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006534 }
Chris Lattner84dff672008-07-11 05:08:55 +00006535 break;
6536 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006537 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006538 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006539 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006540 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006541
6542 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006543 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006544 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6545 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006546 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006547 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006548
6549 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6550 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006551 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006552 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006553 }
Chris Lattner84dff672008-07-11 05:08:55 +00006554 break;
6555 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006556 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006557 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006558 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006559 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006560 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006561 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006562 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6563 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006564 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006565 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006566 }
Chris Lattner84dff672008-07-11 05:08:55 +00006567 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006568 case ICmpInst::ICMP_SGT:
6569 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006570 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006571 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006572 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006573
6574 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006575 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006576 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6577 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006578 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006579 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006580 }
6581 break;
6582 case ICmpInst::ICMP_SGE:
6583 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6584 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006585 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006586 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006587 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006588 break;
6589 case ICmpInst::ICMP_SLE:
6590 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6591 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006592 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006593 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006594 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006595 break;
6596 case ICmpInst::ICMP_UGE:
6597 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6598 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006599 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006600 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006601 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006602 break;
6603 case ICmpInst::ICMP_ULE:
6604 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6605 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006606 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006607 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006608 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006609 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006610 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006611
6612 // Turn a signed comparison into an unsigned one if both operands
6613 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006614 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006615 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6616 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006617 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006618 }
6619
6620 // Test if the ICmpInst instruction is used exclusively by a select as
6621 // part of a minimum or maximum operation. If so, refrain from doing
6622 // any other folding. This helps out other analyses which understand
6623 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6624 // and CodeGen. And in this case, at least one of the comparison
6625 // operands has at least one user besides the compare (the select),
6626 // which would often largely negate the benefit of folding anyway.
6627 if (I.hasOneUse())
6628 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6629 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6630 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6631 return 0;
6632
6633 // See if we are doing a comparison between a constant and an instruction that
6634 // can be folded into the comparison.
6635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006636 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006637 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006638 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006639 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006640 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6641 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006642 }
6643
Chris Lattner01deb9d2007-04-03 17:43:25 +00006644 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006645 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6646 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6647 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006648 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00006649 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00006650 if (RHSC->isNullValue() &&
6651 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6652 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6653 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006654 break;
Chris Lattner6970b662005-04-23 15:31:55 +00006655 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006656 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006657 // block. If in the same block, we're encouraging jump threading. If
6658 // not, we are just pessimizing the code by making an i1 phi.
6659 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006660 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006661 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006662 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006663 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006664 // If either operand of the select is a constant, we can fold the
6665 // comparison into the select arms, which will cause one to be
6666 // constant folded and the select turned into a bitwise or.
6667 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006668 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6669 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6670 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6671 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6672
6673 // We only want to perform this transformation if it will not lead to
6674 // additional code. This is true if either both sides of the select
6675 // fold to a constant (in which case the icmp is replaced with a select
6676 // which will usually simplify) or this is the only user of the
6677 // select (in which case we are trading a select+icmp for a simpler
6678 // select+icmp).
6679 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6680 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006681 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6682 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006683 if (!Op2)
6684 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6685 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006686 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006687 }
Chris Lattner6970b662005-04-23 15:31:55 +00006688 break;
6689 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006690 case Instruction::Call:
6691 // If we have (malloc != null), and if the malloc has a single use, we
6692 // can assume it is successful and remove the malloc.
6693 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6694 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006695 // Need to explicitly erase malloc call here, instead of adding it to
6696 // Worklist, because it won't get DCE'd from the Worklist since
6697 // isInstructionTriviallyDead() returns false for function calls.
6698 // It is OK to replace LHSI/MallocCall with Undef because the
6699 // instruction that uses it will be erased via Worklist.
6700 if (extractMallocCall(LHSI)) {
6701 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6702 EraseInstFromFunction(*LHSI);
6703 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006704 ConstantInt::get(Type::getInt1Ty(*Context),
6705 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006706 }
6707 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6708 if (MallocCall->hasOneUse()) {
6709 MallocCall->replaceAllUsesWith(
6710 UndefValue::get(MallocCall->getType()));
6711 EraseInstFromFunction(*MallocCall);
6712 Worklist.Add(LHSI); // The malloc's bitcast use.
6713 return ReplaceInstUsesWith(I,
6714 ConstantInt::get(Type::getInt1Ty(*Context),
6715 !I.isTrueWhenEqual()));
6716 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006717 }
6718 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00006719 case Instruction::IntToPtr:
6720 // icmp pred inttoptr(X), null -> icmp pred X, 0
6721 if (RHSC->isNullValue() && TD &&
6722 TD->getIntPtrType(RHSC->getContext()) ==
6723 LHSI->getOperand(0)->getType())
6724 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6725 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6726 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00006727
6728 case Instruction::Load:
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006729 // Try to optimize things like "A[i] > 4" to index computations.
Chris Lattner1f12e442010-01-02 08:12:04 +00006730 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00006731 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006732 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6733 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattner34e0c762010-01-02 08:20:51 +00006734 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00006735 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6736 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006737 //errs() << "NOT HANDLED INT: " << *GV << "\n";
Chris Lattner34e0c762010-01-02 08:20:51 +00006738 //errs() << "\t" << *GEP << "\n";
6739 //errs() << "\t " << I << "\n\n\n";
6740 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006741 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006742 }
Chris Lattner6970b662005-04-23 15:31:55 +00006743 }
6744
Reid Spencere4d87aa2006-12-23 06:05:41 +00006745 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006746 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006747 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006748 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006749 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006750 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6751 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006752 return NI;
6753
Reid Spencere4d87aa2006-12-23 06:05:41 +00006754 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006755 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6756 // now.
6757 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6758 if (isa<PointerType>(Op0->getType()) &&
6759 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006760 // We keep moving the cast from the left operand over to the right
6761 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006762 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006763
Chris Lattner57d86372007-01-06 01:45:59 +00006764 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6765 // so eliminate it as well.
6766 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6767 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006768
Chris Lattnerde90b762003-11-03 04:25:02 +00006769 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006770 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006771 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006772 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006773 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006774 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006775 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006776 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006777 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006778 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006779 }
Chris Lattner57d86372007-01-06 01:45:59 +00006780 }
6781
6782 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006783 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006784 // This comes up when you have code like
6785 // int X = A < B;
6786 // if (X) ...
6787 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006788 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006789 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006790 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006791 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006792 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006793
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006794 // See if it's the same type of instruction on the left and right.
6795 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6796 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006797 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006798 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006799 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006800 default: break;
6801 case Instruction::Add:
6802 case Instruction::Sub:
6803 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006804 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006805 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006806 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006807 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6808 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6809 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006810 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006811 ? I.getUnsignedPredicate()
6812 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006813 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006814 Op1I->getOperand(0));
6815 }
6816
6817 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006818 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006819 ? I.getUnsignedPredicate()
6820 : I.getSignedPredicate();
6821 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006822 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006823 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006824 }
6825 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006826 break;
6827 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006828 if (!I.isEquality())
6829 break;
6830
Nick Lewycky5d52c452008-08-21 05:56:10 +00006831 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6832 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6833 // Mask = -1 >> count-trailing-zeros(Cst).
6834 if (!CI->isZero() && !CI->isOne()) {
6835 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006836 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006837 APInt::getLowBitsSet(AP.getBitWidth(),
6838 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006839 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006840 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6841 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006842 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006843 }
6844 }
6845 break;
6846 }
6847 }
6848 }
6849 }
6850
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006851 // ~x < ~y --> y < x
6852 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006853 if (match(Op0, m_Not(m_Value(A))) &&
6854 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006855 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006856 }
6857
Chris Lattner65b72ba2006-09-18 04:22:48 +00006858 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006859 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006860
6861 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006862 if (match(Op0, m_Neg(m_Value(A))) &&
6863 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006864 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006865
Dan Gohman4ae51262009-08-12 16:23:25 +00006866 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006867 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6868 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006869 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006870 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006871 }
6872
Dan Gohman4ae51262009-08-12 16:23:25 +00006873 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006874 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006875 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006876 if (match(B, m_ConstantInt(C1)) &&
6877 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006878 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006879 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006880 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6881 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006882 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006883
6884 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006885 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6886 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6887 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6888 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006889 }
6890 }
6891
Dan Gohman4ae51262009-08-12 16:23:25 +00006892 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006893 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006894 // A == (A^B) -> B == 0
6895 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006896 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006897 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006898 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006899
6900 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006901 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006902 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006903 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006904
6905 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006906 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006907 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006908 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006909
Chris Lattner9c2328e2006-11-14 06:06:06 +00006910 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6911 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006912 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6913 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006914 Value *X = 0, *Y = 0, *Z = 0;
6915
6916 if (A == C) {
6917 X = B; Y = D; Z = A;
6918 } else if (A == D) {
6919 X = B; Y = C; Z = A;
6920 } else if (B == C) {
6921 X = A; Y = D; Z = B;
6922 } else if (B == D) {
6923 X = A; Y = C; Z = B;
6924 }
6925
6926 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006927 Op1 = Builder->CreateXor(X, Y, "tmp");
6928 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006929 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006930 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006931 return &I;
6932 }
6933 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006934 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006935
6936 {
6937 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006938 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006939 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006940 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6941
Chris Lattner2799baf2009-12-21 03:19:28 +00006942 // icmp X, X+Cst
6943 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006944 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006945 }
Chris Lattner7e708292002-06-25 16:13:24 +00006946 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006947}
6948
Chris Lattner2799baf2009-12-21 03:19:28 +00006949/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6950Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6951 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006952 ICmpInst::Predicate Pred,
6953 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006954 // If we have X+0, exit early (simplifying logic below) and let it get folded
6955 // elsewhere. icmp X+0, X -> icmp X, X
6956 if (CI->isZero()) {
6957 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6958 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6959 }
6960
6961 // (X+4) == X -> false.
6962 if (Pred == ICmpInst::ICMP_EQ)
6963 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6964
6965 // (X+4) != X -> true.
6966 if (Pred == ICmpInst::ICMP_NE)
6967 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006968
6969 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6970 bool isNUW = false, isNSW = false;
6971 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6972 isNUW = Add->hasNoUnsignedWrap();
6973 isNSW = Add->hasNoSignedWrap();
6974 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006975
6976 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6977 // so the values can never be equal. Similiarly for all other "or equals"
6978 // operators.
6979
6980 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6981 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6982 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6983 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006984 // If this is an NUW add, then this is always false.
6985 if (isNUW)
6986 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6987
Chris Lattner2799baf2009-12-21 03:19:28 +00006988 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6989 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6990 }
6991
6992 // (X+1) >u X --> X <u (0-1) --> X != 255
6993 // (X+2) >u X --> X <u (0-2) --> X <u 254
6994 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006995 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6996 // If this is an NUW add, then this is always true.
6997 if (isNUW)
6998 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006999 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00007000 }
Chris Lattner2799baf2009-12-21 03:19:28 +00007001
7002 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
7003 ConstantInt *SMax = ConstantInt::get(X->getContext(),
7004 APInt::getSignedMaxValue(BitWidth));
7005
7006 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
7007 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
7008 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
7009 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
7010 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
7011 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00007012 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
7013 // If this is an NSW add, then we have two cases: if the constant is
7014 // positive, then this is always false, if negative, this is always true.
7015 if (isNSW) {
7016 bool isTrue = CI->getValue().isNegative();
7017 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
7018 }
7019
Chris Lattner2799baf2009-12-21 03:19:28 +00007020 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00007021 }
Chris Lattner2799baf2009-12-21 03:19:28 +00007022
7023 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
7024 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
7025 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
7026 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
7027 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
7028 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00007029
7030 // If this is an NSW add, then we have two cases: if the constant is
7031 // positive, then this is always true, if negative, this is always false.
7032 if (isNSW) {
7033 bool isTrue = !CI->getValue().isNegative();
7034 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
7035 }
7036
Chris Lattner2799baf2009-12-21 03:19:28 +00007037 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
7038 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
7039 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
7040}
Chris Lattner562ef782007-06-20 23:46:26 +00007041
7042/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
7043/// and CmpRHS are both known to be integer constants.
7044Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
7045 ConstantInt *DivRHS) {
7046 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
7047 const APInt &CmpRHSV = CmpRHS->getValue();
7048
7049 // FIXME: If the operand types don't match the type of the divide
7050 // then don't attempt this transform. The code below doesn't have the
7051 // logic to deal with a signed divide and an unsigned compare (and
7052 // vice versa). This is because (x /s C1) <s C2 produces different
7053 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
7054 // (x /u C1) <u C2. Simply casting the operands and result won't
7055 // work. :( The if statement below tests that condition and bails
7056 // if it finds it.
7057 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007058 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00007059 return 0;
7060 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00007061 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00007062 if (DivIsSigned && DivRHS->isAllOnesValue())
7063 return 0; // The overflow computation also screws up here
7064 if (DivRHS->isOne())
7065 return 0; // Not worth bothering, and eliminates some funny cases
7066 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00007067
7068 // Compute Prod = CI * DivRHS. We are essentially solving an equation
7069 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
7070 // C2 (CI). By solving for X we can turn this into a range check
7071 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007072 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00007073
7074 // Determine if the product overflows by seeing if the product is
7075 // not equal to the divide. Make sure we do the same kind of divide
7076 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007077 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
7078 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00007079
7080 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00007081 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00007082
Chris Lattner1dbfd482007-06-21 18:11:19 +00007083 // Figure out the interval that is being checked. For example, a comparison
7084 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
7085 // Compute this interval based on the constants involved and the signedness of
7086 // the compare/divide. This computes a half-open interval, keeping track of
7087 // whether either value in the interval overflows. After analysis each
7088 // overflow variable is set to 0 if it's corresponding bound variable is valid
7089 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7090 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00007091 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007092
Chris Lattner562ef782007-06-20 23:46:26 +00007093 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00007094 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00007095 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007096 HiOverflow = LoOverflow = ProdOV;
7097 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007098 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00007099 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007100 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007101 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00007102 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00007103 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00007104 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007105 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
7106 HiOverflow = LoOverflow = ProdOV;
7107 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007108 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007109 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00007110 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007111 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00007112 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7113 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007114 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007115 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00007116 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00007117 true) ? -1 : 0;
7118 }
Chris Lattner562ef782007-06-20 23:46:26 +00007119 }
Dan Gohman76491272008-02-13 22:09:18 +00007120 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007121 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007122 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00007123 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007124 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007125 if (HiBound == DivRHS) { // -INTMIN = INTMIN
7126 HiOverflow = 1; // [INTMIN+1, overflow)
7127 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
7128 }
Dan Gohman76491272008-02-13 22:09:18 +00007129 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007130 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007131 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007132 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007133 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007134 LoOverflow = AddWithOverflow(LoBound, HiBound,
7135 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007136 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00007137 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
7138 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00007139 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007140 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007141 }
7142
Chris Lattner1dbfd482007-06-21 18:11:19 +00007143 // Dividing by a negative swaps the condition. LT <-> GT
7144 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00007145 }
7146
7147 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007148 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00007149 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00007150 case ICmpInst::ICMP_EQ:
7151 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007152 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007153 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007154 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007155 ICmpInst::ICMP_UGE, X, LoBound);
7156 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007157 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007158 ICmpInst::ICMP_ULT, X, HiBound);
7159 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007160 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007161 case ICmpInst::ICMP_NE:
7162 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007163 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007164 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007165 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007166 ICmpInst::ICMP_ULT, X, LoBound);
7167 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007168 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007169 ICmpInst::ICMP_UGE, X, HiBound);
7170 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007171 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007172 case ICmpInst::ICMP_ULT:
7173 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007174 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007175 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007176 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007177 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007178 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007179 case ICmpInst::ICMP_UGT:
7180 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007181 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007182 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007183 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007184 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007185 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007186 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007187 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007188 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007189 }
7190}
7191
7192
Chris Lattner01deb9d2007-04-03 17:43:25 +00007193/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7194///
7195Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7196 Instruction *LHSI,
7197 ConstantInt *RHS) {
7198 const APInt &RHSV = RHS->getValue();
7199
7200 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00007201 case Instruction::Trunc:
7202 if (ICI.isEquality() && LHSI->hasOneUse()) {
7203 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7204 // of the high bits truncated out of x are known.
7205 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7206 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7207 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7208 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7209 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7210
7211 // If all the high bits are known, we can do this xform.
7212 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7213 // Pull in the high bits from known-ones set.
7214 APInt NewRHS(RHS->getValue());
7215 NewRHS.zext(SrcBits);
7216 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007217 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007218 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00007219 }
7220 }
7221 break;
7222
Duncan Sands0091bf22007-04-04 06:42:45 +00007223 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00007224 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7225 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7226 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007227 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7228 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007229 Value *CompareVal = LHSI->getOperand(0);
7230
7231 // If the sign bit of the XorCST is not set, there is no change to
7232 // the operation, just stop using the Xor.
7233 if (!XorCST->getValue().isNegative()) {
7234 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00007235 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007236 return &ICI;
7237 }
7238
7239 // Was the old condition true if the operand is positive?
7240 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7241
7242 // If so, the new one isn't.
7243 isTrueIfPositive ^= true;
7244
7245 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007246 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007247 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007248 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007249 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007250 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007251 }
Nick Lewycky4333f492009-01-31 21:30:05 +00007252
7253 if (LHSI->hasOneUse()) {
7254 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7255 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7256 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007257 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007258 ? ICI.getUnsignedPredicate()
7259 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007260 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007261 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007262 }
7263
7264 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007265 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007266 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007267 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007268 ? ICI.getUnsignedPredicate()
7269 : ICI.getSignedPredicate();
7270 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007271 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007272 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007273 }
7274 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007275 }
7276 break;
7277 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7278 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7279 LHSI->getOperand(0)->hasOneUse()) {
7280 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7281
7282 // If the LHS is an AND of a truncating cast, we can widen the
7283 // and/compare to be the input width without changing the value
7284 // produced, eliminating a cast.
7285 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7286 // We can do this transformation if either the AND constant does not
7287 // have its sign bit set or if it is an equality comparison.
7288 // Extending a relational comparison when we're checking the sign
7289 // bit would not work.
7290 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007291 (ICI.isEquality() ||
7292 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007293 uint32_t BitWidth =
7294 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7295 APInt NewCST = AndCST->getValue();
7296 NewCST.zext(BitWidth);
7297 APInt NewCI = RHSV;
7298 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007299 Value *NewAnd =
7300 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007301 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007302 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00007303 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007304 }
7305 }
7306
7307 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7308 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7309 // happens a LOT in code produced by the C front-end, for bitfield
7310 // access.
7311 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7312 if (Shift && !Shift->isShift())
7313 Shift = 0;
7314
7315 ConstantInt *ShAmt;
7316 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7317 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7318 const Type *AndTy = AndCST->getType(); // Type of the and.
7319
7320 // We can fold this as long as we can't shift unknown bits
7321 // into the mask. This can only happen with signed shift
7322 // rights, as they sign-extend.
7323 if (ShAmt) {
7324 bool CanFold = Shift->isLogicalShift();
7325 if (!CanFold) {
7326 // To test for the bad case of the signed shr, see if any
7327 // of the bits shifted in could be tested after the mask.
7328 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7329 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7330
7331 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7332 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7333 AndCST->getValue()) == 0)
7334 CanFold = true;
7335 }
7336
7337 if (CanFold) {
7338 Constant *NewCst;
7339 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007340 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007341 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007342 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007343
7344 // Check to see if we are shifting out any of the bits being
7345 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007346 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007347 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007348 // If we shifted bits out, the fold is not going to work out.
7349 // As a special case, check to see if this means that the
7350 // result is always true or false now.
7351 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007352 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007353 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007354 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007355 } else {
7356 ICI.setOperand(1, NewCst);
7357 Constant *NewAndCST;
7358 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007359 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007360 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007361 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007362 LHSI->setOperand(1, NewAndCST);
7363 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007364 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007365 return &ICI;
7366 }
7367 }
7368 }
7369
7370 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7371 // preferable because it allows the C<<Y expression to be hoisted out
7372 // of a loop if Y is invariant and X is not.
7373 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007374 ICI.isEquality() && !Shift->isArithmeticShift() &&
7375 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007376 // Compute C << Y.
7377 Value *NS;
7378 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007379 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007380 } else {
7381 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007382 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007383 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007384
7385 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007386 Value *NewAnd =
7387 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007388
7389 ICI.setOperand(0, NewAnd);
7390 return &ICI;
7391 }
7392 }
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007393
7394 // Try to optimize things like "A[i]&42 == 0" to index computations.
7395 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
7396 if (GetElementPtrInst *GEP =
7397 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
7398 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7399 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
7400 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
7401 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
7402 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
7403 return Res;
7404 //errs() << "NOT HANDLED INT: " << *GV << "\n";
7405 //errs() << "\t" << *GEP << "\n";
7406 //errs() << "\t " << I << "\n\n\n";
7407 }
7408 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007409 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00007410
7411 case Instruction::Or: {
7412 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7413 break;
7414 Value *P, *Q;
7415 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7416 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7417 // -> and (icmp eq P, null), (icmp eq Q, null).
7418
7419 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7420 Constant::getNullValue(P->getType()));
7421 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7422 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007423 Instruction *Op;
7424 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7425 Op = BinaryOperator::CreateAnd(ICIP, ICIQ, "");
7426 else
7427 Op = BinaryOperator::CreateOr(ICIP, ICIQ, "");
7428 Op->takeName(&ICI);
7429 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00007430 }
7431 break;
7432 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007433
Chris Lattnera0141b92007-07-15 20:42:37 +00007434 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7435 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7436 if (!ShAmt) break;
7437
7438 uint32_t TypeBits = RHSV.getBitWidth();
7439
7440 // Check that the shift amount is in range. If not, don't perform
7441 // undefined shifts. When the shift is visited it will be
7442 // simplified.
7443 if (ShAmt->uge(TypeBits))
7444 break;
7445
7446 if (ICI.isEquality()) {
7447 // If we are comparing against bits always shifted out, the
7448 // comparison cannot succeed.
7449 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007450 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007451 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007452 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7453 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007454 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007455 return ReplaceInstUsesWith(ICI, Cst);
7456 }
7457
7458 if (LHSI->hasOneUse()) {
7459 // Otherwise strength reduce the shift into an and.
7460 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7461 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007462 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007463 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007464
Chris Lattner74381062009-08-30 07:44:24 +00007465 Value *And =
7466 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007467 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007468 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007469 }
7470 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007471
7472 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7473 bool TrueIfSigned = false;
7474 if (LHSI->hasOneUse() &&
7475 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7476 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007477 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007478 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007479 Value *And =
7480 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007481 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007482 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007483 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007484 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007485 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007486
7487 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007488 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007489 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007490 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007491 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007492
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007493 // Check that the shift amount is in range. If not, don't perform
7494 // undefined shifts. When the shift is visited it will be
7495 // simplified.
7496 uint32_t TypeBits = RHSV.getBitWidth();
7497 if (ShAmt->uge(TypeBits))
7498 break;
7499
7500 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007501
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007502 // If we are comparing against bits always shifted out, the
7503 // comparison cannot succeed.
7504 APInt Comp = RHSV << ShAmtVal;
7505 if (LHSI->getOpcode() == Instruction::LShr)
7506 Comp = Comp.lshr(ShAmtVal);
7507 else
7508 Comp = Comp.ashr(ShAmtVal);
7509
7510 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7511 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007512 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007513 return ReplaceInstUsesWith(ICI, Cst);
7514 }
7515
7516 // Otherwise, check to see if the bits shifted out are known to be zero.
7517 // If so, we can compare against the unshifted value:
7518 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007519 if (LHSI->hasOneUse() &&
7520 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007521 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007522 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007523 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007524 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007525
Evan Chengf30752c2008-04-23 00:38:06 +00007526 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007527 // Otherwise strength reduce the shift into an and.
7528 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007529 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007530
Chris Lattner74381062009-08-30 07:44:24 +00007531 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7532 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007533 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007534 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007535 }
7536 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007537 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007538
7539 case Instruction::SDiv:
7540 case Instruction::UDiv:
7541 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7542 // Fold this div into the comparison, producing a range check.
7543 // Determine, based on the divide type, what the range is being
7544 // checked. If there is an overflow on the low or high side, remember
7545 // it, otherwise compute the range [low, hi) bounding the new value.
7546 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007547 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7548 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7549 DivRHS))
7550 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007551 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007552
7553 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007554 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007555 if (!ICI.isEquality()) {
7556 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7557 if (!LHSC) break;
7558 const APInt &LHSV = LHSC->getValue();
7559
7560 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7561 .subtract(LHSV);
7562
Nick Lewycky4a134af2009-10-25 05:20:17 +00007563 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007564 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007565 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007566 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007567 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007568 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007569 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007570 }
7571 } else {
7572 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007573 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007574 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007575 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007576 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007577 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007578 }
7579 }
7580 }
7581 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007582 }
7583
7584 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7585 if (ICI.isEquality()) {
7586 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7587
7588 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7589 // the second operand is a constant, simplify a bit.
7590 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7591 switch (BO->getOpcode()) {
7592 case Instruction::SRem:
7593 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7594 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7595 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7596 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007597 Value *NewRem =
7598 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7599 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007600 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007601 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007602 }
7603 }
7604 break;
7605 case Instruction::Add:
7606 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7607 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7608 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007609 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007610 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007611 } else if (RHSV == 0) {
7612 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7613 // efficiently invertible, or if the add has just this one use.
7614 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7615
Dan Gohman186a6362009-08-12 16:04:34 +00007616 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007617 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007618 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007619 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007620 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007621 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007622 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007623 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007624 }
7625 }
7626 break;
7627 case Instruction::Xor:
7628 // For the xor case, we can xor two constants together, eliminating
7629 // the explicit xor.
7630 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007631 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007632 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007633
7634 // FALLTHROUGH
7635 case Instruction::Sub:
7636 // Replace (([sub|xor] A, B) != 0) with (A != B)
7637 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007638 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007639 BO->getOperand(1));
7640 break;
7641
7642 case Instruction::Or:
7643 // If bits are being or'd in that are not present in the constant we
7644 // are comparing against, then the comparison could never succeed!
7645 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007646 Constant *NotCI = ConstantExpr::getNot(RHS);
7647 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007648 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007649 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007650 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007651 }
7652 break;
7653
7654 case Instruction::And:
7655 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7656 // If bits are being compared against that are and'd out, then the
7657 // comparison can never succeed!
7658 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007659 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007660 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007661 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007662
7663 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7664 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007665 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007666 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007667 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007668
7669 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007670 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007671 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007672 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007673 ICmpInst::Predicate pred = isICMP_NE ?
7674 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007675 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007676 }
7677
7678 // ((X & ~7) == 0) --> X < 8
7679 if (RHSV == 0 && isHighOnes(BOC)) {
7680 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007681 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007682 ICmpInst::Predicate pred = isICMP_NE ?
7683 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007684 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007685 }
7686 }
7687 default: break;
7688 }
7689 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7690 // Handle icmp {eq|ne} <intrinsic>, intcst.
7691 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007692 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007693 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007694 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007695 return &ICI;
7696 }
7697 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007698 }
7699 return 0;
7700}
7701
7702/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7703/// We only handle extending casts so far.
7704///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007705Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7706 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007707 Value *LHSCIOp = LHSCI->getOperand(0);
7708 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007709 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007710 Value *RHSCIOp;
7711
Chris Lattner8c756c12007-05-05 22:41:33 +00007712 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7713 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007714 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7715 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007716 cast<IntegerType>(DestTy)->getBitWidth()) {
7717 Value *RHSOp = 0;
7718 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007719 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007720 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7721 RHSOp = RHSC->getOperand(0);
7722 // If the pointer types don't match, insert a bitcast.
7723 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007724 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007725 }
7726
7727 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007728 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007729 }
7730
7731 // The code below only handles extension cast instructions, so far.
7732 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007733 if (LHSCI->getOpcode() != Instruction::ZExt &&
7734 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007735 return 0;
7736
Reid Spencere4d87aa2006-12-23 06:05:41 +00007737 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007738 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007739
Reid Spencere4d87aa2006-12-23 06:05:41 +00007740 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007741 // Not an extension from the same type?
7742 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007743 if (RHSCIOp->getType() != LHSCIOp->getType())
7744 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007745
Nick Lewycky4189a532008-01-28 03:48:02 +00007746 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007747 // and the other is a zext), then we can't handle this.
7748 if (CI->getOpcode() != LHSCI->getOpcode())
7749 return 0;
7750
Nick Lewycky4189a532008-01-28 03:48:02 +00007751 // Deal with equality cases early.
7752 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007753 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007754
7755 // A signed comparison of sign extended values simplifies into a
7756 // signed comparison.
7757 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007758 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007759
7760 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007761 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007762 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007763
Reid Spencere4d87aa2006-12-23 06:05:41 +00007764 // If we aren't dealing with a constant on the RHS, exit early
7765 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7766 if (!CI)
7767 return 0;
7768
7769 // Compute the constant that would happen if we truncated to SrcTy then
7770 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007771 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7772 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007773 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007774
7775 // If the re-extended constant didn't change...
7776 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007777 // Deal with equality cases early.
7778 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007779 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007780
7781 // A signed comparison of sign extended values simplifies into a
7782 // signed comparison.
7783 if (isSignedExt && isSignedCmp)
7784 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7785
7786 // The other three cases all fold into an unsigned comparison.
7787 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007788 }
7789
7790 // The re-extended constant changed so the constant cannot be represented
7791 // in the shorter type. Consequently, we cannot emit a simple comparison.
7792
7793 // First, handle some easy cases. We know the result cannot be equal at this
7794 // point so handle the ICI.isEquality() cases
7795 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007796 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007797 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007798 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007799
7800 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7801 // should have been folded away previously and not enter in here.
7802 Value *Result;
7803 if (isSignedCmp) {
7804 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007805 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007806 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007807 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007808 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007809 } else {
7810 // We're performing an unsigned comparison.
7811 if (isSignedExt) {
7812 // We're performing an unsigned comp with a sign extended value.
7813 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007814 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007815 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007816 } else {
7817 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007818 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007819 }
7820 }
7821
7822 // Finally, return the value computed.
7823 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007824 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007825 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007826
7827 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7828 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7829 "ICmp should be folded!");
7830 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007831 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007832 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007833}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007834
Reid Spencer832254e2007-02-02 02:16:23 +00007835Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7836 return commonShiftTransforms(I);
7837}
7838
7839Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7840 return commonShiftTransforms(I);
7841}
7842
7843Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007844 if (Instruction *R = commonShiftTransforms(I))
7845 return R;
7846
7847 Value *Op0 = I.getOperand(0);
7848
7849 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7850 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7851 if (CSI->isAllOnesValue())
7852 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007853
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007854 // See if we can turn a signed shr into an unsigned shr.
7855 if (MaskedValueIsZero(Op0,
7856 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7857 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7858
7859 // Arithmetic shifting an all-sign-bit value is a no-op.
7860 unsigned NumSignBits = ComputeNumSignBits(Op0);
7861 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7862 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007863
Chris Lattner348f6652007-12-06 01:59:46 +00007864 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007865}
7866
7867Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7868 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007869 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007870
7871 // shl X, 0 == X and shr X, 0 == X
7872 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007873 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7874 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007875 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007876
Reid Spencere4d87aa2006-12-23 06:05:41 +00007877 if (isa<UndefValue>(Op0)) {
7878 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007879 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007880 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007882 }
7883 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007884 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7885 return ReplaceInstUsesWith(I, Op0);
7886 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007888 }
7889
Dan Gohman9004c8a2009-05-21 02:28:33 +00007890 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007891 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007892 return &I;
7893
Chris Lattner2eefe512004-04-09 19:05:30 +00007894 // Try to fold constant and into select arguments.
7895 if (isa<Constant>(Op0))
7896 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007897 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007898 return R;
7899
Reid Spencerb83eb642006-10-20 07:07:24 +00007900 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007901 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7902 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007903 return 0;
7904}
7905
Reid Spencerb83eb642006-10-20 07:07:24 +00007906Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007907 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007908 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007909
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007910 // See if we can simplify any instructions used by the instruction whose sole
7911 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007912 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007913
Dan Gohmana119de82009-06-14 23:30:43 +00007914 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7915 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007916 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007917 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007918 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007919 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007920 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007921 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007922 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007923 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007924 }
7925
7926 // ((X*C1) << C2) == (X * (C1 << C2))
7927 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7928 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7929 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007930 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007931 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007932
7933 // Try to fold constant and into select arguments.
7934 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7935 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7936 return R;
7937 if (isa<PHINode>(Op0))
7938 if (Instruction *NV = FoldOpIntoPhi(I))
7939 return NV;
7940
Chris Lattner8999dd32007-12-22 09:07:47 +00007941 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7942 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7943 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7944 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7945 // place. Don't try to do this transformation in this case. Also, we
7946 // require that the input operand is a shift-by-constant so that we have
7947 // confidence that the shifts will get folded together. We could do this
7948 // xform in more cases, but it is unlikely to be profitable.
7949 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7950 isa<ConstantInt>(TrOp->getOperand(1))) {
7951 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007952 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007953 // (shift2 (shift1 & 0x00FF), c2)
7954 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007955
7956 // For logical shifts, the truncation has the effect of making the high
7957 // part of the register be zeros. Emulate this by inserting an AND to
7958 // clear the top bits as needed. This 'and' will usually be zapped by
7959 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007960 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7961 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007962 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7963
7964 // The mask we constructed says what the trunc would do if occurring
7965 // between the shifts. We want to know the effect *after* the second
7966 // shift. We know that it is a logical shift by a constant, so adjust the
7967 // mask as appropriate.
7968 if (I.getOpcode() == Instruction::Shl)
7969 MaskV <<= Op1->getZExtValue();
7970 else {
7971 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7972 MaskV = MaskV.lshr(Op1->getZExtValue());
7973 }
7974
Chris Lattner74381062009-08-30 07:44:24 +00007975 // shift1 & 0x00FF
7976 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7977 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007978
7979 // Return the value truncated to the interesting size.
7980 return new TruncInst(And, I.getType());
7981 }
7982 }
7983
Chris Lattner4d5542c2006-01-06 07:12:35 +00007984 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007985 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7986 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7987 Value *V1, *V2;
7988 ConstantInt *CC;
7989 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007990 default: break;
7991 case Instruction::Add:
7992 case Instruction::And:
7993 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007994 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007995 // These operators commute.
7996 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007997 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007998 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007999 m_Specific(Op1)))) {
8000 Value *YS = // (Y << C)
8001 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
8002 // (X + (Y << C))
8003 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
8004 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00008005 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00008006 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00008007 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00008008 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008009
Chris Lattner150f12a2005-09-18 06:30:59 +00008010 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00008011 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00008012 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00008013 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00008014 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008015 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00008016 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008017 Value *YS = // (Y << C)
8018 Builder->CreateShl(Op0BO->getOperand(0), Op1,
8019 Op0BO->getName());
8020 // X & (CC << C)
8021 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8022 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008023 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00008024 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00008025 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008026
Reid Spencera07cb7d2007-02-02 14:41:37 +00008027 // FALL THROUGH.
8028 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00008029 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00008030 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00008031 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00008032 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008033 Value *YS = // (Y << C)
8034 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8035 // (X + (Y << C))
8036 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
8037 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00008038 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00008039 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00008040 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00008041 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008042
Chris Lattner13d4ab42006-05-31 21:14:00 +00008043 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00008044 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
8045 match(Op0BO->getOperand(0),
8046 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008047 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00008048 cast<BinaryOperator>(Op0BO->getOperand(0))
8049 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008050 Value *YS = // (Y << C)
8051 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8052 // X & (CC << C)
8053 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8054 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00008055
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008056 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00008057 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008058
Chris Lattner11021cb2005-09-18 05:12:10 +00008059 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00008060 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008061 }
8062
8063
8064 // If the operand is an bitwise operator with a constant RHS, and the
8065 // shift is the only use, we can pull it out of the shift.
8066 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
8067 bool isValid = true; // Valid only for And, Or, Xor
8068 bool highBitSet = false; // Transform if high bit of constant set?
8069
8070 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00008071 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00008072 case Instruction::Add:
8073 isValid = isLeftShift;
8074 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00008075 case Instruction::Or:
8076 case Instruction::Xor:
8077 highBitSet = false;
8078 break;
8079 case Instruction::And:
8080 highBitSet = true;
8081 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008082 }
8083
8084 // If this is a signed shift right, and the high bit is modified
8085 // by the logical operation, do not perform the transformation.
8086 // The highBitSet boolean indicates the value of the high bit of
8087 // the constant which would cause it to be modified for this
8088 // operation.
8089 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00008090 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00008091 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008092
8093 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008094 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008095
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008096 Value *NewShift =
8097 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00008098 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008099
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008100 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00008101 NewRHS);
8102 }
8103 }
8104 }
8105 }
8106
Chris Lattnerad0124c2006-01-06 07:52:12 +00008107 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00008108 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8109 if (ShiftOp && !ShiftOp->isShift())
8110 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008111
Reid Spencerb83eb642006-10-20 07:07:24 +00008112 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008113 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008114 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8115 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008116 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8117 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
8118 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00008119
Zhou Sheng4351c642007-04-02 08:20:41 +00008120 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00008121
8122 const IntegerType *Ty = cast<IntegerType>(I.getType());
8123
8124 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00008125 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008126 // If this is oversized composite shift, then unsigned shifts get 0, ashr
8127 // saturates.
8128 if (AmtSum >= TypeBits) {
8129 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00008130 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008131 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
8132 }
8133
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008134 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00008135 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008136 }
8137
8138 if (ShiftOp->getOpcode() == Instruction::LShr &&
8139 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008140 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00008141 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008142
Chris Lattnerb87056f2007-02-05 00:57:54 +00008143 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00008144 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008145 }
8146
8147 if (ShiftOp->getOpcode() == Instruction::AShr &&
8148 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00008149 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00008150 if (AmtSum >= TypeBits)
8151 AmtSum = TypeBits-1;
8152
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008153 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008154
Zhou Shenge9e03f62007-03-28 15:02:20 +00008155 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008156 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008157 }
8158
Chris Lattnerb87056f2007-02-05 00:57:54 +00008159 // Okay, if we get here, one shift must be left, and the other shift must be
8160 // right. See if the amounts are equal.
8161 if (ShiftAmt1 == ShiftAmt2) {
8162 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8163 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00008164 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008165 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008166 }
8167 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8168 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00008169 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008170 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008171 }
8172 // We can simplify ((X << C) >>s C) into a trunc + sext.
8173 // NOTE: we could do this for any C, but that would make 'unusual' integer
8174 // types. For now, just stick to ones well-supported by the code
8175 // generators.
8176 const Type *SExtType = 0;
8177 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00008178 case 1 :
8179 case 8 :
8180 case 16 :
8181 case 32 :
8182 case 64 :
8183 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00008184 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00008185 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008186 default: break;
8187 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008188 if (SExtType)
8189 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008190 // Otherwise, we can't handle it yet.
8191 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00008192 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008193
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008194 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008195 if (I.getOpcode() == Instruction::Shl) {
8196 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8197 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008198 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00008199
Reid Spencer55702aa2007-03-25 21:11:44 +00008200 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008201 return BinaryOperator::CreateAnd(Shift,
8202 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008203 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008204
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008205 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008206 if (I.getOpcode() == Instruction::LShr) {
8207 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008208 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008209
Reid Spencerd5e30f02007-03-26 17:18:58 +00008210 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008211 return BinaryOperator::CreateAnd(Shift,
8212 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00008213 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008214
8215 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8216 } else {
8217 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00008218 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008219
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008220 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008221 if (I.getOpcode() == Instruction::Shl) {
8222 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8223 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008224 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8225 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008226
Reid Spencer55702aa2007-03-25 21:11:44 +00008227 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008228 return BinaryOperator::CreateAnd(Shift,
8229 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008230 }
8231
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008232 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008233 if (I.getOpcode() == Instruction::LShr) {
8234 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008235 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008236
Reid Spencer68d27cf2007-03-26 23:45:51 +00008237 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008238 return BinaryOperator::CreateAnd(Shift,
8239 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008240 }
8241
8242 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008243 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00008244 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00008245 return 0;
8246}
8247
Chris Lattnera1be5662002-05-02 17:06:02 +00008248
Chris Lattnercfd65102005-10-29 04:36:15 +00008249/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8250/// expression. If so, decompose it, returning some value X, such that Val is
8251/// X*Scale+Offset.
8252///
8253static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008254 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008255 assert(Val->getType() == Type::getInt32Ty(*Context) &&
8256 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00008257 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008258 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00008259 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00008260 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00008261 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8262 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8263 if (I->getOpcode() == Instruction::Shl) {
8264 // This is a value scaled by '1 << the shift amt'.
8265 Scale = 1U << RHS->getZExtValue();
8266 Offset = 0;
8267 return I->getOperand(0);
8268 } else if (I->getOpcode() == Instruction::Mul) {
8269 // This value is scaled by 'RHS'.
8270 Scale = RHS->getZExtValue();
8271 Offset = 0;
8272 return I->getOperand(0);
8273 } else if (I->getOpcode() == Instruction::Add) {
8274 // We have X+C. Check to see if we really have (X*C2)+C1,
8275 // where C1 is divisible by C2.
8276 unsigned SubScale;
8277 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00008278 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8279 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00008280 Offset += RHS->getZExtValue();
8281 Scale = SubScale;
8282 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00008283 }
8284 }
8285 }
8286
8287 // Otherwise, we can't look past this.
8288 Scale = 1;
8289 Offset = 0;
8290 return Val;
8291}
8292
8293
Chris Lattnerb3f83972005-10-24 06:03:58 +00008294/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8295/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008296Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00008297 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008298 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00008299
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008300 BuilderTy AllocaBuilder(*Builder);
8301 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8302
Chris Lattnerb53c2382005-10-24 06:22:12 +00008303 // Remove any uses of AI that are dead.
8304 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008305
Chris Lattnerb53c2382005-10-24 06:22:12 +00008306 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8307 Instruction *User = cast<Instruction>(*UI++);
8308 if (isInstructionTriviallyDead(User)) {
8309 while (UI != E && *UI == User)
8310 ++UI; // If this instruction uses AI more than once, don't break UI.
8311
Chris Lattnerb53c2382005-10-24 06:22:12 +00008312 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008313 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008314 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008315 }
8316 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008317
8318 // This requires TargetData to get the alloca alignment and size information.
8319 if (!TD) return 0;
8320
Chris Lattnerb3f83972005-10-24 06:03:58 +00008321 // Get the type really allocated and the type casted to.
8322 const Type *AllocElTy = AI.getAllocatedType();
8323 const Type *CastElTy = PTy->getElementType();
8324 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008325
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008326 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8327 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008328 if (CastElTyAlign < AllocElTyAlign) return 0;
8329
Chris Lattner39387a52005-10-24 06:35:18 +00008330 // If the allocation has multiple uses, only promote it if we are strictly
8331 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008332 // same, we open the door to infinite loops of various kinds. (A reference
8333 // from a dbg.declare doesn't count as a use for this purpose.)
8334 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8335 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008336
Duncan Sands777d2302009-05-09 07:06:46 +00008337 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8338 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008339 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008340
Chris Lattner455fcc82005-10-29 03:19:53 +00008341 // See if we can satisfy the modulus by pulling a scale out of the array
8342 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008343 unsigned ArraySizeScale;
8344 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008345 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00008346 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8347 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00008348
Chris Lattner455fcc82005-10-29 03:19:53 +00008349 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8350 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008351 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8352 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008353
Chris Lattner455fcc82005-10-29 03:19:53 +00008354 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8355 Value *Amt = 0;
8356 if (Scale == 1) {
8357 Amt = NumElements;
8358 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00008359 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008360 // Insert before the alloca, not before the cast.
8361 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008362 }
8363
Jeff Cohen86796be2007-04-04 16:58:57 +00008364 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008365 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008366 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008367 }
8368
Victor Hernandez7b929da2009-10-23 21:09:37 +00008369 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008370 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008371 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008372
Dale Johannesena0a66372009-03-05 00:39:02 +00008373 // If the allocation has one real use plus a dbg.declare, just remove the
8374 // declare.
8375 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8376 EraseInstFromFunction(*DI);
8377 }
8378 // If the allocation has multiple real uses, insert a cast and change all
8379 // things that used it to use the new cast. This will also hack on CI, but it
8380 // will die soon.
8381 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008382 // New is the allocation instruction, pointer typed. AI is the original
8383 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008384 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008385 AI.replaceAllUsesWith(NewCast);
8386 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008387 return ReplaceInstUsesWith(CI, New);
8388}
8389
Chris Lattner70074e02006-05-13 02:06:03 +00008390/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008391/// and return it as type Ty without inserting any new casts and without
8392/// changing the computed value. This is used by code that tries to decide
8393/// whether promoting or shrinking integer operations to wider or smaller types
8394/// will allow us to eliminate a truncate or extend.
8395///
8396/// This is a truncation operation if Ty is smaller than V->getType(), or an
8397/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008398///
8399/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8400/// should return true if trunc(V) can be computed by computing V in the smaller
8401/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8402/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8403/// efficiently truncated.
8404///
8405/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8406/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8407/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008408bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008409 unsigned CastOpc,
8410 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008411 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008412 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008413 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008414
8415 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008416 if (!I) return false;
8417
Dan Gohman6de29f82009-06-15 22:12:54 +00008418 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008419
Chris Lattner951626b2007-08-02 06:11:14 +00008420 // If this is an extension or truncate, we can often eliminate it.
8421 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8422 // If this is a cast from the destination type, we can trivially eliminate
8423 // it, and this will remove a cast overall.
8424 if (I->getOperand(0)->getType() == Ty) {
8425 // If the first operand is itself a cast, and is eliminable, do not count
8426 // this as an eliminable cast. We would prefer to eliminate those two
8427 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008428 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008429 ++NumCastsRemoved;
8430 return true;
8431 }
8432 }
8433
8434 // We can't extend or shrink something that has multiple uses: doing so would
8435 // require duplicating the instruction in general, which isn't profitable.
8436 if (!I->hasOneUse()) return false;
8437
Evan Chengf35fd542009-01-15 17:01:23 +00008438 unsigned Opc = I->getOpcode();
8439 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008440 case Instruction::Add:
8441 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008442 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008443 case Instruction::And:
8444 case Instruction::Or:
8445 case Instruction::Xor:
8446 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008447 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008448 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008449 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008450 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008451
Eli Friedman070a9812009-07-13 22:46:01 +00008452 case Instruction::UDiv:
8453 case Instruction::URem: {
8454 // UDiv and URem can be truncated if all the truncated bits are zero.
8455 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8456 uint32_t BitWidth = Ty->getScalarSizeInBits();
8457 if (BitWidth < OrigBitWidth) {
8458 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8459 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8460 MaskedValueIsZero(I->getOperand(1), Mask)) {
8461 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8462 NumCastsRemoved) &&
8463 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8464 NumCastsRemoved);
8465 }
8466 }
8467 break;
8468 }
Chris Lattner46b96052006-11-29 07:18:39 +00008469 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008470 // If we are truncating the result of this SHL, and if it's a shift of a
8471 // constant amount, we can always perform a SHL in a smaller type.
8472 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008473 uint32_t BitWidth = Ty->getScalarSizeInBits();
8474 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008475 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008476 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008477 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008478 }
8479 break;
8480 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008481 // If this is a truncate of a logical shr, we can truncate it to a smaller
8482 // lshr iff we know that the bits we would otherwise be shifting in are
8483 // already zeros.
8484 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008485 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8486 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008487 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008488 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008489 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8490 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008491 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008492 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008493 }
8494 }
Chris Lattner46b96052006-11-29 07:18:39 +00008495 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008496 case Instruction::ZExt:
8497 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008498 case Instruction::Trunc:
8499 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008500 // can safely replace it. Note that replacing it does not reduce the number
8501 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008502 if (Opc == CastOpc)
8503 return true;
8504
8505 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008506 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008507 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008508 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008509 case Instruction::Select: {
8510 SelectInst *SI = cast<SelectInst>(I);
8511 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008512 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008513 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008514 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008515 }
Chris Lattner8114b712008-06-18 04:00:49 +00008516 case Instruction::PHI: {
8517 // We can change a phi if we can change all operands.
8518 PHINode *PN = cast<PHINode>(I);
8519 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8520 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008521 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008522 return false;
8523 return true;
8524 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008525 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008526 // TODO: Can handle more cases here.
8527 break;
8528 }
8529
8530 return false;
8531}
8532
8533/// EvaluateInDifferentType - Given an expression that
8534/// CanEvaluateInDifferentType returns true for, actually insert the code to
8535/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008536Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008537 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008538 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008539 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008540
8541 // Otherwise, it must be an instruction.
8542 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008543 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008544 unsigned Opc = I->getOpcode();
8545 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008546 case Instruction::Add:
8547 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008548 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008549 case Instruction::And:
8550 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008551 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008552 case Instruction::AShr:
8553 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008554 case Instruction::Shl:
8555 case Instruction::UDiv:
8556 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008557 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008558 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008559 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008560 break;
8561 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008562 case Instruction::Trunc:
8563 case Instruction::ZExt:
8564 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008565 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008566 // just return the source. There's no need to insert it because it is not
8567 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008568 if (I->getOperand(0)->getType() == Ty)
8569 return I->getOperand(0);
8570
Chris Lattner8114b712008-06-18 04:00:49 +00008571 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008572 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008573 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008574 case Instruction::Select: {
8575 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8576 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8577 Res = SelectInst::Create(I->getOperand(0), True, False);
8578 break;
8579 }
Chris Lattner8114b712008-06-18 04:00:49 +00008580 case Instruction::PHI: {
8581 PHINode *OPN = cast<PHINode>(I);
8582 PHINode *NPN = PHINode::Create(Ty);
8583 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8584 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8585 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8586 }
8587 Res = NPN;
8588 break;
8589 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008590 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008591 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008592 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008593 break;
8594 }
8595
Chris Lattner8114b712008-06-18 04:00:49 +00008596 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008597 return InsertNewInstBefore(Res, *I);
8598}
8599
Reid Spencer3da59db2006-11-27 01:05:10 +00008600/// @brief Implement the transforms common to all CastInst visitors.
8601Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008602 Value *Src = CI.getOperand(0);
8603
Dan Gohman23d9d272007-05-11 21:10:54 +00008604 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008605 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008606 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008607 if (Instruction::CastOps opc =
8608 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8609 // The first cast (CSrc) is eliminable so we need to fix up or replace
8610 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008611 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008612 }
8613 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008614
Reid Spencer3da59db2006-11-27 01:05:10 +00008615 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008616 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8617 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8618 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008619
8620 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008621 if (isa<PHINode>(Src)) {
8622 // We don't do this if this would create a PHI node with an illegal type if
8623 // it is currently legal.
8624 if (!isa<IntegerType>(Src->getType()) ||
8625 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008626 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008627 if (Instruction *NV = FoldOpIntoPhi(CI))
8628 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008629 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008630
Reid Spencer3da59db2006-11-27 01:05:10 +00008631 return 0;
8632}
8633
Chris Lattner46cd5a12009-01-09 05:44:56 +00008634/// FindElementAtOffset - Given a type and a constant offset, determine whether
8635/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008636/// the specified offset. If so, fill them into NewIndices and return the
8637/// resultant element type, otherwise return null.
8638static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8639 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008640 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008641 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008642 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008643 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008644
8645 // Start with the index over the outer type. Note that the type size
8646 // might be zero (even if the offset isn't zero) if the indexed type
8647 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008648 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008649 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008650 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008651 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008652 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008653
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008654 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008655 if (Offset < 0) {
8656 --FirstIdx;
8657 Offset += TySize;
8658 assert(Offset >= 0);
8659 }
8660 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8661 }
8662
Owen Andersoneed707b2009-07-24 23:12:02 +00008663 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008664
8665 // Index into the types. If we fail, set OrigBase to null.
8666 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008667 // Indexing into tail padding between struct/array elements.
8668 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008669 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008670
Chris Lattner46cd5a12009-01-09 05:44:56 +00008671 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8672 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008673 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8674 "Offset must stay within the indexed type");
8675
Chris Lattner46cd5a12009-01-09 05:44:56 +00008676 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008677 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008678
8679 Offset -= SL->getElementOffset(Elt);
8680 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008681 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008682 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008683 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008684 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008685 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008686 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008687 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008688 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008689 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008690 }
8691 }
8692
Chris Lattner3914f722009-01-24 01:00:13 +00008693 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008694}
8695
Chris Lattnerd3e28342007-04-27 17:44:50 +00008696/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8697Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8698 Value *Src = CI.getOperand(0);
8699
Chris Lattnerd3e28342007-04-27 17:44:50 +00008700 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008701 // If casting the result of a getelementptr instruction with no offset, turn
8702 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008703 if (GEP->hasAllZeroIndices()) {
8704 // Changing the cast operand is usually not a good idea but it is safe
8705 // here because the pointer operand is being replaced with another
8706 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008707 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008708 CI.setOperand(0, GEP->getOperand(0));
8709 return &CI;
8710 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008711
8712 // If the GEP has a single use, and the base pointer is a bitcast, and the
8713 // GEP computes a constant offset, see if we can convert these three
8714 // instructions into fewer. This typically happens with unions and other
8715 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008716 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008717 if (GEP->hasAllConstantIndices()) {
8718 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008719 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008720 int64_t Offset = OffsetV->getSExtValue();
8721
8722 // Get the base pointer input of the bitcast, and the type it points to.
8723 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8724 const Type *GEPIdxTy =
8725 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008726 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008727 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008728 // If we were able to index down into an element, create the GEP
8729 // and bitcast the result. This eliminates one bitcast, potentially
8730 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008731 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8732 Builder->CreateInBoundsGEP(OrigBase,
8733 NewIndices.begin(), NewIndices.end()) :
8734 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008735 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008736
Chris Lattner46cd5a12009-01-09 05:44:56 +00008737 if (isa<BitCastInst>(CI))
8738 return new BitCastInst(NGEP, CI.getType());
8739 assert(isa<PtrToIntInst>(CI));
8740 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008741 }
8742 }
8743 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008744 }
8745
8746 return commonCastTransforms(CI);
8747}
8748
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008749/// commonIntCastTransforms - This function implements the common transforms
8750/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008751Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8752 if (Instruction *Result = commonCastTransforms(CI))
8753 return Result;
8754
8755 Value *Src = CI.getOperand(0);
8756 const Type *SrcTy = Src->getType();
8757 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008758 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8759 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008760
Reid Spencer3da59db2006-11-27 01:05:10 +00008761 // See if we can simplify any instructions used by the LHS whose sole
8762 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008763 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008764 return &CI;
8765
8766 // If the source isn't an instruction or has more than one use then we
8767 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008768 Instruction *SrcI = dyn_cast<Instruction>(Src);
8769 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008770 return 0;
8771
Chris Lattnerc739cd62007-03-03 05:27:34 +00008772 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008773 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008774 // Only do this if the dest type is a simple type, don't convert the
8775 // expression tree to something weird like i93 unless the source is also
8776 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008777 if ((isa<VectorType>(DestTy) ||
8778 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8779 CanEvaluateInDifferentType(SrcI, DestTy,
8780 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008781 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008782 // eliminates the cast, so it is always a win. If this is a zero-extension,
8783 // we need to do an AND to maintain the clear top-part of the computation,
8784 // so we require that the input have eliminated at least one cast. If this
8785 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008786 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008787 bool DoXForm = false;
8788 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008789 switch (CI.getOpcode()) {
8790 default:
8791 // All the others use floating point so we shouldn't actually
8792 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008793 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008794 case Instruction::Trunc:
8795 DoXForm = true;
8796 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008797 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008798 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008799
Chris Lattner39c27ed2009-01-31 19:05:27 +00008800 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008801 // If it's unnecessary to issue an AND to clear the high bits, it's
8802 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008803 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008804 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8805 if (MaskedValueIsZero(TryRes, Mask))
8806 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008807
8808 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008809 if (TryI->use_empty())
8810 EraseInstFromFunction(*TryI);
8811 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008812 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008813 }
Evan Chengf35fd542009-01-15 17:01:23 +00008814 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008815 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008816 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008817 // If we do not have to emit the truncate + sext pair, then it's always
8818 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008819 //
8820 // It's not safe to eliminate the trunc + sext pair if one of the
8821 // eliminated cast is a truncate. e.g.
8822 // t2 = trunc i32 t1 to i16
8823 // t3 = sext i16 t2 to i32
8824 // !=
8825 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008826 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008827 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8828 if (NumSignBits > (DestBitSize - SrcBitSize))
8829 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008830
8831 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008832 if (TryI->use_empty())
8833 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008834 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008835 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008836 }
Evan Chengf35fd542009-01-15 17:01:23 +00008837 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008838
8839 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008840 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8841 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008842 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8843 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008844 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008845 // Just replace this cast with the result.
8846 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008847
Reid Spencer3da59db2006-11-27 01:05:10 +00008848 assert(Res->getType() == DestTy);
8849 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008850 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008851 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008852 // Just replace this cast with the result.
8853 return ReplaceInstUsesWith(CI, Res);
8854 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008855 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008856
8857 // If the high bits are already zero, just replace this cast with the
8858 // result.
8859 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8860 if (MaskedValueIsZero(Res, Mask))
8861 return ReplaceInstUsesWith(CI, Res);
8862
8863 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008864 Constant *C = ConstantInt::get(*Context,
8865 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008866 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008867 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008868 case Instruction::SExt: {
8869 // If the high bits are already filled with sign bit, just replace this
8870 // cast with the result.
8871 unsigned NumSignBits = ComputeNumSignBits(Res);
8872 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008873 return ReplaceInstUsesWith(CI, Res);
8874
Reid Spencer3da59db2006-11-27 01:05:10 +00008875 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008876 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008877 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008878 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008879 }
8880 }
8881
8882 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8883 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8884
8885 switch (SrcI->getOpcode()) {
8886 case Instruction::Add:
8887 case Instruction::Mul:
8888 case Instruction::And:
8889 case Instruction::Or:
8890 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008891 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008892 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8893 // Don't insert two casts unless at least one can be eliminated.
8894 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008895 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008896 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8897 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008898 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008899 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008900 }
8901 }
8902
8903 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8904 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8905 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008906 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008907 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008908 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008909 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008910 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008911 }
8912 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008913
Eli Friedman65445c52009-07-13 21:45:57 +00008914 case Instruction::Shl: {
8915 // Canonicalize trunc inside shl, if we can.
8916 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8917 if (CI && DestBitSize < SrcBitSize &&
8918 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008919 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8920 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008921 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008922 }
8923 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008924 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008925 }
8926 return 0;
8927}
8928
Chris Lattner8a9f5712007-04-11 06:57:46 +00008929Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008930 if (Instruction *Result = commonIntCastTransforms(CI))
8931 return Result;
8932
8933 Value *Src = CI.getOperand(0);
8934 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008935 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8936 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008937
8938 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008939 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008940 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008941 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008942 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008943 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008944 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008945
Chris Lattner4f9797d2009-03-24 18:15:30 +00008946 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8947 ConstantInt *ShAmtV = 0;
8948 Value *ShiftOp = 0;
8949 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008950 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008951 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8952
8953 // Get a mask for the bits shifting in.
8954 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8955 if (MaskedValueIsZero(ShiftOp, Mask)) {
8956 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008957 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008958
8959 // Okay, we can shrink this. Truncate the input, then return a new
8960 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008961 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008962 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008963 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008964 }
8965 }
Chris Lattner9956c052009-11-08 19:23:30 +00008966
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008967 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008968}
8969
Evan Chengb98a10e2008-03-24 00:21:34 +00008970/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8971/// in order to eliminate the icmp.
8972Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8973 bool DoXform) {
8974 // If we are just checking for a icmp eq of a single bit and zext'ing it
8975 // to an integer, then shift the bit to the appropriate place and then
8976 // cast to integer to avoid the comparison.
8977 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8978 const APInt &Op1CV = Op1C->getValue();
8979
8980 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8981 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8982 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8983 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8984 if (!DoXform) return ICI;
8985
8986 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008987 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008988 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008989 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008990 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008991 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008992
8993 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008994 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008995 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008996 }
8997
8998 return ReplaceInstUsesWith(CI, In);
8999 }
9000
9001
9002
9003 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
9004 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
9005 // zext (X == 1) to i32 --> X iff X has only the low bit set.
9006 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
9007 // zext (X != 0) to i32 --> X iff X has only the low bit set.
9008 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
9009 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
9010 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
9011 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
9012 // This only works for EQ and NE
9013 ICI->isEquality()) {
9014 // If Op1C some other power of two, convert:
9015 uint32_t BitWidth = Op1C->getType()->getBitWidth();
9016 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9017 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9018 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
9019
9020 APInt KnownZeroMask(~KnownZero);
9021 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
9022 if (!DoXform) return ICI;
9023
9024 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
9025 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
9026 // (X&4) == 2 --> false
9027 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00009028 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00009029 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00009030 return ReplaceInstUsesWith(CI, Res);
9031 }
9032
9033 uint32_t ShiftAmt = KnownZeroMask.logBase2();
9034 Value *In = ICI->getOperand(0);
9035 if (ShiftAmt) {
9036 // Perform a logical shr by shiftamt.
9037 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009038 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
9039 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00009040 }
9041
9042 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00009043 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009044 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00009045 }
9046
9047 if (CI.getType() == In->getType())
9048 return ReplaceInstUsesWith(CI, In);
9049 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009050 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00009051 }
9052 }
9053 }
9054
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009055 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
9056 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
9057 // may lead to additional simplifications.
9058 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
9059 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
9060 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009061 Value *LHS = ICI->getOperand(0);
9062 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009063
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009064 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
9065 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
9066 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9067 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
9068 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009069
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009070 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
9071 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
9072 APInt UnknownBit = ~KnownBits;
9073 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009074 if (!DoXform) return ICI;
9075
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009076 Value *Result = Builder->CreateXor(LHS, RHS);
9077
9078 // Mask off any bits that are set and won't be shifted away.
9079 if (KnownOneLHS.uge(UnknownBit))
9080 Result = Builder->CreateAnd(Result,
9081 ConstantInt::get(ITy, UnknownBit));
9082
9083 // Shift the bit we're testing down to the lsb.
9084 Result = Builder->CreateLShr(
9085 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
9086
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009087 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009088 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
9089 Result->takeName(ICI);
9090 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009091 }
9092 }
9093 }
9094 }
9095
Evan Chengb98a10e2008-03-24 00:21:34 +00009096 return 0;
9097}
9098
Chris Lattner8a9f5712007-04-11 06:57:46 +00009099Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009100 // If one of the common conversion will work ..
9101 if (Instruction *Result = commonIntCastTransforms(CI))
9102 return Result;
9103
9104 Value *Src = CI.getOperand(0);
9105
Chris Lattnera84f47c2009-02-17 20:47:23 +00009106 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9107 // types and if the sizes are just right we can convert this into a logical
9108 // 'and' which will be much cheaper than the pair of casts.
9109 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
9110 // Get the sizes of the types involved. We know that the intermediate type
9111 // will be smaller than A or C, but don't know the relation between A and C.
9112 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009113 unsigned SrcSize = A->getType()->getScalarSizeInBits();
9114 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9115 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00009116 // If we're actually extending zero bits, then if
9117 // SrcSize < DstSize: zext(a & mask)
9118 // SrcSize == DstSize: a & mask
9119 // SrcSize > DstSize: trunc(a) & mask
9120 if (SrcSize < DstSize) {
9121 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009122 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009123 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009124 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009125 }
9126
9127 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00009128 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009129 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009130 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009131 }
9132 if (SrcSize > DstSize) {
9133 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009134 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00009135 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00009136 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009137 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00009138 }
9139 }
9140
Evan Chengb98a10e2008-03-24 00:21:34 +00009141 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9142 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00009143
Evan Chengb98a10e2008-03-24 00:21:34 +00009144 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9145 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9146 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9147 // of the (zext icmp) will be transformed.
9148 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9149 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9150 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9151 (transformZExtICmp(LHS, CI, false) ||
9152 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009153 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9154 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009155 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00009156 }
Evan Chengb98a10e2008-03-24 00:21:34 +00009157 }
9158
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009159 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00009160 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9161 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9162 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9163 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009164 if (TI0->getType() == CI.getType())
9165 return
9166 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00009167 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00009168 }
9169
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009170 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9171 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9172 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9173 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9174 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9175 And->getOperand(1) == C)
9176 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9177 Value *TI0 = TI->getOperand(0);
9178 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009179 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009180 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009181 return BinaryOperator::CreateXor(NewAnd, ZC);
9182 }
9183 }
9184
Reid Spencer3da59db2006-11-27 01:05:10 +00009185 return 0;
9186}
9187
Chris Lattner8a9f5712007-04-11 06:57:46 +00009188Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00009189 if (Instruction *I = commonIntCastTransforms(CI))
9190 return I;
9191
Chris Lattner8a9f5712007-04-11 06:57:46 +00009192 Value *Src = CI.getOperand(0);
9193
Dan Gohman1975d032008-10-30 20:40:10 +00009194 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00009195 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00009196 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00009197 Constant::getAllOnesValue(CI.getType()),
9198 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00009199
9200 // See if the value being truncated is already sign extended. If so, just
9201 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00009202 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00009203 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009204 unsigned OpBits = Op->getType()->getScalarSizeInBits();
9205 unsigned MidBits = Src->getType()->getScalarSizeInBits();
9206 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00009207 unsigned NumSignBits = ComputeNumSignBits(Op);
9208
9209 if (OpBits == DestBits) {
9210 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9211 // bits, it is already ready.
9212 if (NumSignBits > DestBits-MidBits)
9213 return ReplaceInstUsesWith(CI, Op);
9214 } else if (OpBits < DestBits) {
9215 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9216 // bits, just sext from i32.
9217 if (NumSignBits > OpBits-MidBits)
9218 return new SExtInst(Op, CI.getType(), "tmp");
9219 } else {
9220 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9221 // bits, just truncate to i32.
9222 if (NumSignBits > OpBits-MidBits)
9223 return new TruncInst(Op, CI.getType(), "tmp");
9224 }
9225 }
Chris Lattner46bbad22008-08-06 07:35:52 +00009226
9227 // If the input is a shl/ashr pair of a same constant, then this is a sign
9228 // extension from a smaller value. If we could trust arbitrary bitwidth
9229 // integers, we could turn this into a truncate to the smaller bit and then
9230 // use a sext for the whole extension. Since we don't, look deeper and check
9231 // for a truncate. If the source and dest are the same type, eliminate the
9232 // trunc and extend and just do shifts. For example, turn:
9233 // %a = trunc i32 %i to i8
9234 // %b = shl i8 %a, 6
9235 // %c = ashr i8 %b, 6
9236 // %d = sext i8 %c to i32
9237 // into:
9238 // %a = shl i32 %i, 30
9239 // %d = ashr i32 %a, 30
9240 Value *A = 0;
9241 ConstantInt *BA = 0, *CA = 0;
9242 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00009243 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00009244 BA == CA && isa<TruncInst>(A)) {
9245 Value *I = cast<TruncInst>(A)->getOperand(0);
9246 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009247 unsigned MidSize = Src->getType()->getScalarSizeInBits();
9248 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00009249 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00009250 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009251 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00009252 return BinaryOperator::CreateAShr(I, ShAmtV);
9253 }
9254 }
9255
Chris Lattnerba417832007-04-11 06:12:58 +00009256 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009257}
9258
Chris Lattnerb7530652008-01-27 05:29:54 +00009259/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9260/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00009261static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009262 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00009263 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00009264 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00009265 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9266 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00009267 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00009268 return 0;
9269}
9270
9271/// LookThroughFPExtensions - If this is an fp extension instruction, look
9272/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00009273static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00009274 if (Instruction *I = dyn_cast<Instruction>(V))
9275 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00009276 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009277
9278 // If this value is a constant, return the constant in the smallest FP type
9279 // that can accurately represent it. This allows us to turn
9280 // (float)((double)X+2.0) into x+2.0f.
9281 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009282 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009283 return V; // No constant folding of this.
9284 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00009285 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009286 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00009287 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009288 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00009289 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009290 return V;
9291 // Don't try to shrink to various long double types.
9292 }
9293
9294 return V;
9295}
9296
9297Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9298 if (Instruction *I = commonCastTransforms(CI))
9299 return I;
9300
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009301 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00009302 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009303 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009304 // many builtins (sqrt, etc).
9305 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9306 if (OpI && OpI->hasOneUse()) {
9307 switch (OpI->getOpcode()) {
9308 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009309 case Instruction::FAdd:
9310 case Instruction::FSub:
9311 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009312 case Instruction::FDiv:
9313 case Instruction::FRem:
9314 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00009315 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9316 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009317 if (LHSTrunc->getType() != SrcTy &&
9318 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009319 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009320 // If the source types were both smaller than the destination type of
9321 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009322 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9323 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009324 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9325 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009326 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009327 }
9328 }
9329 break;
9330 }
9331 }
9332 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009333}
9334
9335Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9336 return commonCastTransforms(CI);
9337}
9338
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009339Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009340 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9341 if (OpI == 0)
9342 return commonCastTransforms(FI);
9343
9344 // fptoui(uitofp(X)) --> X
9345 // fptoui(sitofp(X)) --> X
9346 // This is safe if the intermediate type has enough bits in its mantissa to
9347 // accurately represent all values of X. For example, do not do this with
9348 // i64->float->i64. This is also safe for sitofp case, because any negative
9349 // 'X' value would cause an undefined result for the fptoui.
9350 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9351 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009352 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009353 OpI->getType()->getFPMantissaWidth())
9354 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009355
9356 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009357}
9358
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009359Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009360 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9361 if (OpI == 0)
9362 return commonCastTransforms(FI);
9363
9364 // fptosi(sitofp(X)) --> X
9365 // fptosi(uitofp(X)) --> X
9366 // This is safe if the intermediate type has enough bits in its mantissa to
9367 // accurately represent all values of X. For example, do not do this with
9368 // i64->float->i64. This is also safe for sitofp case, because any negative
9369 // 'X' value would cause an undefined result for the fptoui.
9370 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9371 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009372 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009373 OpI->getType()->getFPMantissaWidth())
9374 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009375
9376 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009377}
9378
9379Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9380 return commonCastTransforms(CI);
9381}
9382
9383Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9384 return commonCastTransforms(CI);
9385}
9386
Chris Lattnera0e69692009-03-24 18:35:40 +00009387Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9388 // If the destination integer type is smaller than the intptr_t type for
9389 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9390 // trunc to be exposed to other transforms. Don't do this for extending
9391 // ptrtoint's, because we don't know if the target sign or zero extends its
9392 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009393 if (TD &&
9394 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009395 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9396 TD->getIntPtrType(CI.getContext()),
9397 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009398 return new TruncInst(P, CI.getType());
9399 }
9400
Chris Lattnerd3e28342007-04-27 17:44:50 +00009401 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009402}
9403
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009404Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009405 // If the source integer type is larger than the intptr_t type for
9406 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9407 // allows the trunc to be exposed to other transforms. Don't do this for
9408 // extending inttoptr's, because we don't know if the target sign or zero
9409 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009410 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009411 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009412 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9413 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009414 return new IntToPtrInst(P, CI.getType());
9415 }
9416
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009417 if (Instruction *I = commonCastTransforms(CI))
9418 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009419
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009420 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009421}
9422
Chris Lattnerd3e28342007-04-27 17:44:50 +00009423Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009424 // If the operands are integer typed then apply the integer transforms,
9425 // otherwise just apply the common ones.
9426 Value *Src = CI.getOperand(0);
9427 const Type *SrcTy = Src->getType();
9428 const Type *DestTy = CI.getType();
9429
Eli Friedman7e25d452009-07-13 20:53:00 +00009430 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009431 if (Instruction *I = commonPointerCastTransforms(CI))
9432 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009433 } else {
9434 if (Instruction *Result = commonCastTransforms(CI))
9435 return Result;
9436 }
9437
9438
9439 // Get rid of casts from one type to the same type. These are useless and can
9440 // be replaced by the operand.
9441 if (DestTy == Src->getType())
9442 return ReplaceInstUsesWith(CI, Src);
9443
Reid Spencer3da59db2006-11-27 01:05:10 +00009444 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009445 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9446 const Type *DstElTy = DstPTy->getElementType();
9447 const Type *SrcElTy = SrcPTy->getElementType();
9448
Nate Begeman83ad90a2008-03-31 00:22:16 +00009449 // If the address spaces don't match, don't eliminate the bitcast, which is
9450 // required for changing types.
9451 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9452 return 0;
9453
Victor Hernandez83d63912009-09-18 22:35:49 +00009454 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009455 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009456 // There is no need to modify malloc calls because it is their bitcast that
9457 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009458 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009459 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9460 return V;
9461
Chris Lattnerd717c182007-05-05 22:32:24 +00009462 // If the source and destination are pointers, and this cast is equivalent
9463 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009464 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009465 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009466 unsigned NumZeros = 0;
9467 while (SrcElTy != DstElTy &&
9468 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9469 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9470 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9471 ++NumZeros;
9472 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009473
Chris Lattnerd3e28342007-04-27 17:44:50 +00009474 // If we found a path from the src to dest, create the getelementptr now.
9475 if (SrcElTy == DstElTy) {
9476 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009477 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9478 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009479 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009480 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009481
Eli Friedman2451a642009-07-18 23:06:53 +00009482 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9483 if (DestVTy->getNumElements() == 1) {
9484 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009485 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009486 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009487 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009488 }
9489 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9490 }
9491 }
9492
9493 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9494 if (SrcVTy->getNumElements() == 1) {
9495 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009496 Value *Elem =
9497 Builder->CreateExtractElement(Src,
9498 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009499 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9500 }
9501 }
9502 }
9503
Reid Spencer3da59db2006-11-27 01:05:10 +00009504 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9505 if (SVI->hasOneUse()) {
9506 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9507 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009508 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009509 cast<VectorType>(DestTy)->getNumElements() ==
9510 SVI->getType()->getNumElements() &&
9511 SVI->getType()->getNumElements() ==
9512 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009513 CastInst *Tmp;
9514 // If either of the operands is a cast from CI.getType(), then
9515 // evaluating the shuffle in the casted destination's type will allow
9516 // us to eliminate at least one cast.
9517 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9518 Tmp->getOperand(0)->getType() == DestTy) ||
9519 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9520 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009521 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9522 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009523 // Return a new shuffle vector. Use the same element ID's, as we
9524 // know the vector types match #elts.
9525 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009526 }
9527 }
9528 }
9529 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009530 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009531}
9532
Chris Lattnere576b912004-04-09 23:46:01 +00009533/// GetSelectFoldableOperands - We want to turn code that looks like this:
9534/// %C = or %A, %B
9535/// %D = select %cond, %C, %A
9536/// into:
9537/// %C = select %cond, %B, 0
9538/// %D = or %A, %C
9539///
9540/// Assuming that the specified instruction is an operand to the select, return
9541/// a bitmask indicating which operands of this instruction are foldable if they
9542/// equal the other incoming value of the select.
9543///
9544static unsigned GetSelectFoldableOperands(Instruction *I) {
9545 switch (I->getOpcode()) {
9546 case Instruction::Add:
9547 case Instruction::Mul:
9548 case Instruction::And:
9549 case Instruction::Or:
9550 case Instruction::Xor:
9551 return 3; // Can fold through either operand.
9552 case Instruction::Sub: // Can only fold on the amount subtracted.
9553 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009554 case Instruction::LShr:
9555 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009556 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009557 default:
9558 return 0; // Cannot fold
9559 }
9560}
9561
9562/// GetSelectFoldableConstant - For the same transformation as the previous
9563/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009564static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009565 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009566 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009567 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009568 case Instruction::Add:
9569 case Instruction::Sub:
9570 case Instruction::Or:
9571 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009572 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009573 case Instruction::LShr:
9574 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009575 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009576 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009577 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009578 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009579 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009580 }
9581}
9582
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009583/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9584/// have the same opcode and only one use each. Try to simplify this.
9585Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9586 Instruction *FI) {
9587 if (TI->getNumOperands() == 1) {
9588 // If this is a non-volatile load or a cast from the same type,
9589 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009590 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009591 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9592 return 0;
9593 } else {
9594 return 0; // unknown unary op.
9595 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009596
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009597 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009598 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009599 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009600 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009601 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009602 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009603 }
9604
Reid Spencer832254e2007-02-02 02:16:23 +00009605 // Only handle binary operators here.
9606 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009607 return 0;
9608
9609 // Figure out if the operations have any operands in common.
9610 Value *MatchOp, *OtherOpT, *OtherOpF;
9611 bool MatchIsOpZero;
9612 if (TI->getOperand(0) == FI->getOperand(0)) {
9613 MatchOp = TI->getOperand(0);
9614 OtherOpT = TI->getOperand(1);
9615 OtherOpF = FI->getOperand(1);
9616 MatchIsOpZero = true;
9617 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9618 MatchOp = TI->getOperand(1);
9619 OtherOpT = TI->getOperand(0);
9620 OtherOpF = FI->getOperand(0);
9621 MatchIsOpZero = false;
9622 } else if (!TI->isCommutative()) {
9623 return 0;
9624 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9625 MatchOp = TI->getOperand(0);
9626 OtherOpT = TI->getOperand(1);
9627 OtherOpF = FI->getOperand(0);
9628 MatchIsOpZero = true;
9629 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9630 MatchOp = TI->getOperand(1);
9631 OtherOpT = TI->getOperand(0);
9632 OtherOpF = FI->getOperand(1);
9633 MatchIsOpZero = true;
9634 } else {
9635 return 0;
9636 }
9637
9638 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009639 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9640 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009641 InsertNewInstBefore(NewSI, SI);
9642
9643 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9644 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009645 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009646 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009647 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009648 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009649 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009650 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009651}
9652
Evan Chengde621922009-03-31 20:42:45 +00009653static bool isSelect01(Constant *C1, Constant *C2) {
9654 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9655 if (!C1I)
9656 return false;
9657 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9658 if (!C2I)
9659 return false;
9660 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9661}
9662
9663/// FoldSelectIntoOp - Try fold the select into one of the operands to
9664/// facilitate further optimization.
9665Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9666 Value *FalseVal) {
9667 // See the comment above GetSelectFoldableOperands for a description of the
9668 // transformation we are doing here.
9669 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9670 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9671 !isa<Constant>(FalseVal)) {
9672 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9673 unsigned OpToFold = 0;
9674 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9675 OpToFold = 1;
9676 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9677 OpToFold = 2;
9678 }
9679
9680 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009681 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009682 Value *OOp = TVI->getOperand(2-OpToFold);
9683 // Avoid creating select between 2 constants unless it's selecting
9684 // between 0 and 1.
9685 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9686 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9687 InsertNewInstBefore(NewSel, SI);
9688 NewSel->takeName(TVI);
9689 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9690 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009691 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009692 }
9693 }
9694 }
9695 }
9696 }
9697
9698 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9699 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9700 !isa<Constant>(TrueVal)) {
9701 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9702 unsigned OpToFold = 0;
9703 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9704 OpToFold = 1;
9705 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9706 OpToFold = 2;
9707 }
9708
9709 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009710 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009711 Value *OOp = FVI->getOperand(2-OpToFold);
9712 // Avoid creating select between 2 constants unless it's selecting
9713 // between 0 and 1.
9714 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9715 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9716 InsertNewInstBefore(NewSel, SI);
9717 NewSel->takeName(FVI);
9718 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9719 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009720 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009721 }
9722 }
9723 }
9724 }
9725 }
9726
9727 return 0;
9728}
9729
Dan Gohman81b28ce2008-09-16 18:46:06 +00009730/// visitSelectInstWithICmp - Visit a SelectInst that has an
9731/// ICmpInst as its first operand.
9732///
9733Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9734 ICmpInst *ICI) {
9735 bool Changed = false;
9736 ICmpInst::Predicate Pred = ICI->getPredicate();
9737 Value *CmpLHS = ICI->getOperand(0);
9738 Value *CmpRHS = ICI->getOperand(1);
9739 Value *TrueVal = SI.getTrueValue();
9740 Value *FalseVal = SI.getFalseValue();
9741
9742 // Check cases where the comparison is with a constant that
9743 // can be adjusted to fit the min/max idiom. We may edit ICI in
9744 // place here, so make sure the select is the only user.
9745 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009746 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009747 switch (Pred) {
9748 default: break;
9749 case ICmpInst::ICMP_ULT:
9750 case ICmpInst::ICMP_SLT: {
9751 // X < MIN ? T : F --> F
9752 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9753 return ReplaceInstUsesWith(SI, FalseVal);
9754 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009755 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009756 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9757 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9758 Pred = ICmpInst::getSwappedPredicate(Pred);
9759 CmpRHS = AdjustedRHS;
9760 std::swap(FalseVal, TrueVal);
9761 ICI->setPredicate(Pred);
9762 ICI->setOperand(1, CmpRHS);
9763 SI.setOperand(1, TrueVal);
9764 SI.setOperand(2, FalseVal);
9765 Changed = true;
9766 }
9767 break;
9768 }
9769 case ICmpInst::ICMP_UGT:
9770 case ICmpInst::ICMP_SGT: {
9771 // X > MAX ? T : F --> F
9772 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9773 return ReplaceInstUsesWith(SI, FalseVal);
9774 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009775 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009776 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9777 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9778 Pred = ICmpInst::getSwappedPredicate(Pred);
9779 CmpRHS = AdjustedRHS;
9780 std::swap(FalseVal, TrueVal);
9781 ICI->setPredicate(Pred);
9782 ICI->setOperand(1, CmpRHS);
9783 SI.setOperand(1, TrueVal);
9784 SI.setOperand(2, FalseVal);
9785 Changed = true;
9786 }
9787 break;
9788 }
9789 }
9790
Dan Gohman1975d032008-10-30 20:40:10 +00009791 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9792 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009793 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009794 if (match(TrueVal, m_ConstantInt<-1>()) &&
9795 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009796 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009797 else if (match(TrueVal, m_ConstantInt<0>()) &&
9798 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009799 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9800
Dan Gohman1975d032008-10-30 20:40:10 +00009801 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9802 // If we are just checking for a icmp eq of a single bit and zext'ing it
9803 // to an integer, then shift the bit to the appropriate place and then
9804 // cast to integer to avoid the comparison.
9805 const APInt &Op1CV = CI->getValue();
9806
9807 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9808 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9809 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009810 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009811 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009812 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009813 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009814 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009815 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009816 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009817 if (In->getType() != SI.getType())
9818 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009819 true/*SExt*/, "tmp", ICI);
9820
9821 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009822 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009823 In->getName()+".not"), *ICI);
9824
9825 return ReplaceInstUsesWith(SI, In);
9826 }
9827 }
9828 }
9829
Dan Gohman81b28ce2008-09-16 18:46:06 +00009830 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9831 // Transform (X == Y) ? X : Y -> Y
9832 if (Pred == ICmpInst::ICMP_EQ)
9833 return ReplaceInstUsesWith(SI, FalseVal);
9834 // Transform (X != Y) ? X : Y -> X
9835 if (Pred == ICmpInst::ICMP_NE)
9836 return ReplaceInstUsesWith(SI, TrueVal);
9837 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9838
9839 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9840 // Transform (X == Y) ? Y : X -> X
9841 if (Pred == ICmpInst::ICMP_EQ)
9842 return ReplaceInstUsesWith(SI, FalseVal);
9843 // Transform (X != Y) ? Y : X -> Y
9844 if (Pred == ICmpInst::ICMP_NE)
9845 return ReplaceInstUsesWith(SI, TrueVal);
9846 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9847 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009848 return Changed ? &SI : 0;
9849}
9850
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009851
Chris Lattner7f239582009-10-22 00:17:26 +00009852/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9853/// PHI node (but the two may be in different blocks). See if the true/false
9854/// values (V) are live in all of the predecessor blocks of the PHI. For
9855/// example, cases like this cannot be mapped:
9856///
9857/// X = phi [ C1, BB1], [C2, BB2]
9858/// Y = add
9859/// Z = select X, Y, 0
9860///
9861/// because Y is not live in BB1/BB2.
9862///
9863static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9864 const SelectInst &SI) {
9865 // If the value is a non-instruction value like a constant or argument, it
9866 // can always be mapped.
9867 const Instruction *I = dyn_cast<Instruction>(V);
9868 if (I == 0) return true;
9869
9870 // If V is a PHI node defined in the same block as the condition PHI, we can
9871 // map the arguments.
9872 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9873
9874 if (const PHINode *VP = dyn_cast<PHINode>(I))
9875 if (VP->getParent() == CondPHI->getParent())
9876 return true;
9877
9878 // Otherwise, if the PHI and select are defined in the same block and if V is
9879 // defined in a different block, then we can transform it.
9880 if (SI.getParent() == CondPHI->getParent() &&
9881 I->getParent() != CondPHI->getParent())
9882 return true;
9883
9884 // Otherwise we have a 'hard' case and we can't tell without doing more
9885 // detailed dominator based analysis, punt.
9886 return false;
9887}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009888
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009889/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9890/// SPF2(SPF1(A, B), C)
9891Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9892 SelectPatternFlavor SPF1,
9893 Value *A, Value *B,
9894 Instruction &Outer,
9895 SelectPatternFlavor SPF2, Value *C) {
9896 if (C == A || C == B) {
9897 // MAX(MAX(A, B), B) -> MAX(A, B)
9898 // MIN(MIN(a, b), a) -> MIN(a, b)
9899 if (SPF1 == SPF2)
9900 return ReplaceInstUsesWith(Outer, Inner);
9901
9902 // MAX(MIN(a, b), a) -> a
9903 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009904 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9905 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9906 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9907 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009908 return ReplaceInstUsesWith(Outer, C);
9909 }
9910
9911 // TODO: MIN(MIN(A, 23), 97)
9912 return 0;
9913}
9914
9915
9916
9917
Chris Lattner3d69f462004-03-12 05:52:32 +00009918Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009919 Value *CondVal = SI.getCondition();
9920 Value *TrueVal = SI.getTrueValue();
9921 Value *FalseVal = SI.getFalseValue();
9922
9923 // select true, X, Y -> X
9924 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009925 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009926 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009927
9928 // select C, X, X -> X
9929 if (TrueVal == FalseVal)
9930 return ReplaceInstUsesWith(SI, TrueVal);
9931
Chris Lattnere87597f2004-10-16 18:11:37 +00009932 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9933 return ReplaceInstUsesWith(SI, FalseVal);
9934 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9935 return ReplaceInstUsesWith(SI, TrueVal);
9936 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9937 if (isa<Constant>(TrueVal))
9938 return ReplaceInstUsesWith(SI, TrueVal);
9939 else
9940 return ReplaceInstUsesWith(SI, FalseVal);
9941 }
9942
Owen Anderson1d0be152009-08-13 21:58:54 +00009943 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009944 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009945 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009946 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009947 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009948 } else {
9949 // Change: A = select B, false, C --> A = and !B, C
9950 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009951 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009952 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009953 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009954 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009955 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009956 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009957 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009958 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009959 } else {
9960 // Change: A = select B, C, true --> A = or !B, C
9961 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009962 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009963 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009964 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009965 }
9966 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009967
9968 // select a, b, a -> a&b
9969 // select a, a, b -> a|b
9970 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009971 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009972 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009973 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009974 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009975
Chris Lattner2eefe512004-04-09 19:05:30 +00009976 // Selecting between two integer constants?
9977 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9978 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009979 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009980 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009981 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009982 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009983 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009984 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009985 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009986 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009987 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009988 }
Chris Lattner457dd822004-06-09 07:59:58 +00009989
Reid Spencere4d87aa2006-12-23 06:05:41 +00009990 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009991 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009992 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009993 // non-constant value, eliminate this whole mess. This corresponds to
9994 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009995 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009996 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009997 cast<Constant>(IC->getOperand(1))->isNullValue())
9998 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9999 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +000010000 isa<ConstantInt>(ICA->getOperand(1)) &&
10001 (ICA->getOperand(1) == TrueValC ||
10002 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +000010003 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
10004 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +000010005 // know whether we have a icmp_ne or icmp_eq and whether the
10006 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +000010007 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +000010008 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +000010009 Value *V = ICA;
10010 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010011 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +000010012 Instruction::Xor, V, ICA->getOperand(1)), SI);
10013 return ReplaceInstUsesWith(SI, V);
10014 }
Chris Lattnerb8456462006-09-20 04:44:59 +000010015 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +000010016 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010017
10018 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +000010019 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
10020 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +000010021 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +000010022 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
10023 // This is not safe in general for floating point:
10024 // consider X== -0, Y== +0.
10025 // It becomes safe if either operand is a nonzero constant.
10026 ConstantFP *CFPt, *CFPf;
10027 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10028 !CFPt->getValueAPF().isZero()) ||
10029 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10030 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +000010031 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +000010032 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010033 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +000010034 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +000010035 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +000010036 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +000010037
Reid Spencere4d87aa2006-12-23 06:05:41 +000010038 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +000010039 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +000010040 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
10041 // This is not safe in general for floating point:
10042 // consider X== -0, Y== +0.
10043 // It becomes safe if either operand is a nonzero constant.
10044 ConstantFP *CFPt, *CFPf;
10045 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10046 !CFPt->getValueAPF().isZero()) ||
10047 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10048 !CFPf->getValueAPF().isZero()))
10049 return ReplaceInstUsesWith(SI, FalseVal);
10050 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010051 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +000010052 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
10053 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +000010054 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +000010055 }
Dan Gohman81b28ce2008-09-16 18:46:06 +000010056 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +000010057 }
10058
10059 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +000010060 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
10061 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
10062 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +000010063
Chris Lattner87875da2005-01-13 22:52:24 +000010064 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
10065 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
10066 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +000010067 Instruction *AddOp = 0, *SubOp = 0;
10068
Chris Lattner6fb5a4a2005-01-19 21:50:18 +000010069 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
10070 if (TI->getOpcode() == FI->getOpcode())
10071 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
10072 return IV;
10073
10074 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
10075 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010076 if ((TI->getOpcode() == Instruction::Sub &&
10077 FI->getOpcode() == Instruction::Add) ||
10078 (TI->getOpcode() == Instruction::FSub &&
10079 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010080 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010081 } else if ((FI->getOpcode() == Instruction::Sub &&
10082 TI->getOpcode() == Instruction::Add) ||
10083 (FI->getOpcode() == Instruction::FSub &&
10084 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010085 AddOp = TI; SubOp = FI;
10086 }
10087
10088 if (AddOp) {
10089 Value *OtherAddOp = 0;
10090 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
10091 OtherAddOp = AddOp->getOperand(1);
10092 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
10093 OtherAddOp = AddOp->getOperand(0);
10094 }
10095
10096 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +000010097 // So at this point we know we have (Y -> OtherAddOp):
10098 // select C, (add X, Y), (sub X, Z)
10099 Value *NegVal; // Compute -Z
10100 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000010101 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +000010102 } else {
10103 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +000010104 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +000010105 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +000010106 }
Chris Lattner97f37a42006-02-24 18:05:58 +000010107
10108 Value *NewTrueOp = OtherAddOp;
10109 Value *NewFalseOp = NegVal;
10110 if (AddOp != TI)
10111 std::swap(NewTrueOp, NewFalseOp);
10112 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010113 SelectInst::Create(CondVal, NewTrueOp,
10114 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +000010115
10116 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010117 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +000010118 }
10119 }
10120 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010121
Chris Lattnere576b912004-04-09 23:46:01 +000010122 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +000010123 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010124 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +000010125 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010126
10127 // MAX(MAX(a, b), a) -> MAX(a, b)
10128 // MIN(MIN(a, b), a) -> MIN(a, b)
10129 // MAX(MIN(a, b), a) -> a
10130 // MIN(MAX(a, b), a) -> a
10131 Value *LHS, *RHS, *LHS2, *RHS2;
10132 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10133 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10134 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
10135 SI, SPF, RHS))
10136 return R;
10137 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10138 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10139 SI, SPF, LHS))
10140 return R;
10141 }
10142
10143 // TODO.
10144 // ABS(-X) -> ABS(X)
10145 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +000010146 }
Chris Lattnera1df33c2005-04-24 07:30:14 +000010147
Chris Lattner7f239582009-10-22 00:17:26 +000010148 // See if we can fold the select into a phi node if the condition is a select.
10149 if (isa<PHINode>(SI.getCondition()))
10150 // The true/false values have to be live in the PHI predecessor's blocks.
10151 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10152 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10153 if (Instruction *NV = FoldOpIntoPhi(SI))
10154 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +000010155
Chris Lattnera1df33c2005-04-24 07:30:14 +000010156 if (BinaryOperator::isNot(CondVal)) {
10157 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10158 SI.setOperand(1, FalseVal);
10159 SI.setOperand(2, TrueVal);
10160 return &SI;
10161 }
10162
Chris Lattner3d69f462004-03-12 05:52:32 +000010163 return 0;
10164}
10165
Dan Gohmaneee962e2008-04-10 18:43:06 +000010166/// EnforceKnownAlignment - If the specified pointer points to an object that
10167/// we control, modify the object's alignment to PrefAlign. This isn't
10168/// often possible though. If alignment is important, a more reliable approach
10169/// is to simply align all global variables and allocation instructions to
10170/// their preferred alignment from the beginning.
10171///
10172static unsigned EnforceKnownAlignment(Value *V,
10173 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +000010174
Dan Gohmaneee962e2008-04-10 18:43:06 +000010175 User *U = dyn_cast<User>(V);
10176 if (!U) return Align;
10177
Dan Gohmanca178902009-07-17 20:47:02 +000010178 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010179 default: break;
10180 case Instruction::BitCast:
10181 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10182 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +000010183 // If all indexes are zero, it is just the alignment of the base pointer.
10184 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +000010185 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +000010186 if (!isa<Constant>(*i) ||
10187 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +000010188 AllZeroOperands = false;
10189 break;
10190 }
Chris Lattnerf2369f22007-08-09 19:05:49 +000010191
10192 if (AllZeroOperands) {
10193 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010194 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +000010195 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010196 break;
Chris Lattner95a959d2006-03-06 20:18:44 +000010197 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010198 }
10199
10200 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10201 // If there is a large requested alignment and we can, bump up the alignment
10202 // of the global.
10203 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +000010204 if (GV->getAlignment() >= PrefAlign)
10205 Align = GV->getAlignment();
10206 else {
10207 GV->setAlignment(PrefAlign);
10208 Align = PrefAlign;
10209 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010210 }
Chris Lattner42ebefa2009-09-27 21:42:46 +000010211 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10212 // If there is a requested alignment and if this is an alloca, round up.
10213 if (AI->getAlignment() >= PrefAlign)
10214 Align = AI->getAlignment();
10215 else {
10216 AI->setAlignment(PrefAlign);
10217 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +000010218 }
10219 }
10220
10221 return Align;
10222}
10223
10224/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10225/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
10226/// and it is more than the alignment of the ultimate object, see if we can
10227/// increase the alignment of the ultimate object, making this check succeed.
10228unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10229 unsigned PrefAlign) {
10230 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10231 sizeof(PrefAlign) * CHAR_BIT;
10232 APInt Mask = APInt::getAllOnesValue(BitWidth);
10233 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10234 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10235 unsigned TrailZ = KnownZero.countTrailingOnes();
10236 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10237
10238 if (PrefAlign > Align)
10239 Align = EnforceKnownAlignment(V, Align, PrefAlign);
10240
10241 // We don't need to make any adjustment.
10242 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +000010243}
10244
Chris Lattnerf497b022008-01-13 23:50:23 +000010245Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010246 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +000010247 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +000010248 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010249 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +000010250
10251 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010252 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010253 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +000010254 return MI;
10255 }
10256
10257 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10258 // load/store.
10259 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10260 if (MemOpLength == 0) return 0;
10261
Chris Lattner37ac6082008-01-14 00:28:35 +000010262 // Source and destination pointer types are always "i8*" for intrinsic. See
10263 // if the size is something we can handle with a single primitive load/store.
10264 // A single load+store correctly handles overlapping memory in the memmove
10265 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +000010266 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010267 if (Size == 0) return MI; // Delete this mem transfer.
10268
10269 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +000010270 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +000010271
Chris Lattner37ac6082008-01-14 00:28:35 +000010272 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +000010273 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +000010274 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +000010275
10276 // Memcpy forces the use of i8* for the source and destination. That means
10277 // that if you're using memcpy to move one double around, you'll get a cast
10278 // from double* to i8*. We'd much rather use a double load+store rather than
10279 // an i64 load+store, here because this improves the odds that the source or
10280 // dest address will be promotable. See if we can find a better type than the
10281 // integer datatype.
10282 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10283 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010284 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010285 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10286 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +000010287 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010288 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10289 if (STy->getNumElements() == 1)
10290 SrcETy = STy->getElementType(0);
10291 else
10292 break;
10293 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10294 if (ATy->getNumElements() == 1)
10295 SrcETy = ATy->getElementType();
10296 else
10297 break;
10298 } else
10299 break;
10300 }
10301
Dan Gohman8f8e2692008-05-23 01:52:21 +000010302 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +000010303 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010304 }
10305 }
10306
10307
Chris Lattnerf497b022008-01-13 23:50:23 +000010308 // If the memcpy/memmove provides better alignment info than we can
10309 // infer, use it.
10310 SrcAlign = std::max(SrcAlign, CopyAlign);
10311 DstAlign = std::max(DstAlign, CopyAlign);
10312
Chris Lattner08142f22009-08-30 19:47:22 +000010313 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10314 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010315 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10316 InsertNewInstBefore(L, *MI);
10317 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10318
10319 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010320 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010321 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010322}
Chris Lattner3d69f462004-03-12 05:52:32 +000010323
Chris Lattner69ea9d22008-04-30 06:39:11 +000010324Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10325 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010326 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010327 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010328 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010329 return MI;
10330 }
10331
10332 // Extract the length and alignment and fill if they are constant.
10333 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10334 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +000010335 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010336 return 0;
10337 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010338 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010339
10340 // If the length is zero, this is a no-op
10341 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10342
10343 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10344 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010345 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010346
10347 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010348 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010349
10350 // Alignment 0 is identity for alignment 1 for memset, but not store.
10351 if (Alignment == 0) Alignment = 1;
10352
10353 // Extract the fill value and store.
10354 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010355 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010356 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010357
10358 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010359 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010360 return MI;
10361 }
10362
10363 return 0;
10364}
10365
10366
Chris Lattner8b0ea312006-01-13 20:11:04 +000010367/// visitCallInst - CallInst simplification. This mostly only handles folding
10368/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10369/// the heavy lifting.
10370///
Chris Lattner9fe38862003-06-19 17:00:31 +000010371Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010372 if (isFreeCall(&CI))
10373 return visitFree(CI);
10374
Chris Lattneraab6ec42009-05-13 17:39:14 +000010375 // If the caller function is nounwind, mark the call as nounwind, even if the
10376 // callee isn't.
10377 if (CI.getParent()->getParent()->doesNotThrow() &&
10378 !CI.doesNotThrow()) {
10379 CI.setDoesNotThrow();
10380 return &CI;
10381 }
10382
Chris Lattner8b0ea312006-01-13 20:11:04 +000010383 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10384 if (!II) return visitCallSite(&CI);
10385
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010386 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10387 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010388 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010389 bool Changed = false;
10390
10391 // memmove/cpy/set of zero bytes is a noop.
10392 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10393 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10394
Chris Lattner35b9e482004-10-12 04:52:52 +000010395 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010396 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010397 // Replace the instruction with just byte operations. We would
10398 // transform other cases to loads/stores, but we don't know if
10399 // alignment is sufficient.
10400 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010401 }
10402
Chris Lattner35b9e482004-10-12 04:52:52 +000010403 // If we have a memmove and the source operation is a constant global,
10404 // then the source and dest pointers can't alias, so we can change this
10405 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010406 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010407 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10408 if (GVSrc->isConstant()) {
10409 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010410 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10411 const Type *Tys[1];
10412 Tys[0] = CI.getOperand(3)->getType();
10413 CI.setOperand(0,
10414 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010415 Changed = true;
10416 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010417 }
Chris Lattnera935db82008-05-28 05:30:41 +000010418
Eli Friedman0c826d92009-12-17 21:07:31 +000010419 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010420 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010421 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010422 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010423 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010424
Chris Lattner95a959d2006-03-06 20:18:44 +000010425 // If we can determine a pointer alignment that is bigger than currently
10426 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010427 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010428 if (Instruction *I = SimplifyMemTransfer(MI))
10429 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010430 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10431 if (Instruction *I = SimplifyMemSet(MSI))
10432 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010433 }
10434
Chris Lattner8b0ea312006-01-13 20:11:04 +000010435 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010436 }
10437
10438 switch (II->getIntrinsicID()) {
10439 default: break;
10440 case Intrinsic::bswap:
10441 // bswap(bswap(x)) -> x
10442 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10443 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10444 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010445
10446 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10447 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10448 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10449 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10450 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10451 TI->getType()->getPrimitiveSizeInBits();
10452 Value *CV = ConstantInt::get(Operand->getType(), C);
10453 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10454 return new TruncInst(V, TI->getType());
10455 }
10456 }
10457
Chris Lattner0521e3c2008-06-18 04:33:20 +000010458 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010459 case Intrinsic::powi:
10460 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10461 // powi(x, 0) -> 1.0
10462 if (Power->isZero())
10463 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10464 // powi(x, 1) -> x
10465 if (Power->isOne())
10466 return ReplaceInstUsesWith(CI, II->getOperand(1));
10467 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010468 if (Power->isAllOnesValue())
10469 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10470 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010471 }
10472 break;
10473
Chris Lattner2bbac752009-11-26 21:42:47 +000010474 case Intrinsic::uadd_with_overflow: {
10475 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10476 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10477 uint32_t BitWidth = IT->getBitWidth();
10478 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010479 APInt LHSKnownZero(BitWidth, 0);
10480 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010481 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10482 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10483 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10484
10485 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010486 APInt RHSKnownZero(BitWidth, 0);
10487 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010488 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10489 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10490 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10491 if (LHSKnownNegative && RHSKnownNegative) {
10492 // The sign bit is set in both cases: this MUST overflow.
10493 // Create a simple add instruction, and insert it into the struct.
10494 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10495 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010496 Constant *V[] = {
10497 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10498 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010499 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10500 return InsertValueInst::Create(Struct, Add, 0);
10501 }
10502
10503 if (LHSKnownPositive && RHSKnownPositive) {
10504 // The sign bit is clear in both cases: this CANNOT overflow.
10505 // Create a simple add instruction, and insert it into the struct.
10506 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10507 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010508 Constant *V[] = {
10509 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10510 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010511 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10512 return InsertValueInst::Create(Struct, Add, 0);
10513 }
10514 }
10515 }
10516 // FALL THROUGH uadd into sadd
10517 case Intrinsic::sadd_with_overflow:
10518 // Canonicalize constants into the RHS.
10519 if (isa<Constant>(II->getOperand(1)) &&
10520 !isa<Constant>(II->getOperand(2))) {
10521 Value *LHS = II->getOperand(1);
10522 II->setOperand(1, II->getOperand(2));
10523 II->setOperand(2, LHS);
10524 return II;
10525 }
10526
10527 // X + undef -> undef
10528 if (isa<UndefValue>(II->getOperand(2)))
10529 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10530
10531 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10532 // X + 0 -> {X, false}
10533 if (RHS->isZero()) {
10534 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010535 UndefValue::get(II->getOperand(0)->getType()),
10536 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010537 };
10538 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10539 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10540 }
10541 }
10542 break;
10543 case Intrinsic::usub_with_overflow:
10544 case Intrinsic::ssub_with_overflow:
10545 // undef - X -> undef
10546 // X - undef -> undef
10547 if (isa<UndefValue>(II->getOperand(1)) ||
10548 isa<UndefValue>(II->getOperand(2)))
10549 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10550
10551 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10552 // X - 0 -> {X, false}
10553 if (RHS->isZero()) {
10554 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010555 UndefValue::get(II->getOperand(1)->getType()),
10556 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010557 };
10558 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10559 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10560 }
10561 }
10562 break;
10563 case Intrinsic::umul_with_overflow:
10564 case Intrinsic::smul_with_overflow:
10565 // Canonicalize constants into the RHS.
10566 if (isa<Constant>(II->getOperand(1)) &&
10567 !isa<Constant>(II->getOperand(2))) {
10568 Value *LHS = II->getOperand(1);
10569 II->setOperand(1, II->getOperand(2));
10570 II->setOperand(2, LHS);
10571 return II;
10572 }
10573
10574 // X * undef -> undef
10575 if (isa<UndefValue>(II->getOperand(2)))
10576 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10577
10578 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10579 // X*0 -> {0, false}
10580 if (RHSI->isZero())
10581 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10582
10583 // X * 1 -> {X, false}
10584 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010585 Constant *V[] = {
10586 UndefValue::get(II->getOperand(1)->getType()),
10587 ConstantInt::getFalse(*Context)
10588 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010589 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010590 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010591 }
10592 }
10593 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010594 case Intrinsic::ppc_altivec_lvx:
10595 case Intrinsic::ppc_altivec_lvxl:
10596 case Intrinsic::x86_sse_loadu_ps:
10597 case Intrinsic::x86_sse2_loadu_pd:
10598 case Intrinsic::x86_sse2_loadu_dq:
10599 // Turn PPC lvx -> load if the pointer is known aligned.
10600 // Turn X86 loadups -> load if the pointer is known aligned.
10601 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010602 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10603 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010604 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010605 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010606 break;
10607 case Intrinsic::ppc_altivec_stvx:
10608 case Intrinsic::ppc_altivec_stvxl:
10609 // Turn stvx -> store if the pointer is known aligned.
10610 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10611 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010612 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010613 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010614 return new StoreInst(II->getOperand(1), Ptr);
10615 }
10616 break;
10617 case Intrinsic::x86_sse_storeu_ps:
10618 case Intrinsic::x86_sse2_storeu_pd:
10619 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010620 // Turn X86 storeu -> store if the pointer is known aligned.
10621 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10622 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010623 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010624 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010625 return new StoreInst(II->getOperand(2), Ptr);
10626 }
10627 break;
10628
10629 case Intrinsic::x86_sse_cvttss2si: {
10630 // These intrinsics only demands the 0th element of its input vector. If
10631 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010632 unsigned VWidth =
10633 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10634 APInt DemandedElts(VWidth, 1);
10635 APInt UndefElts(VWidth, 0);
10636 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010637 UndefElts)) {
10638 II->setOperand(1, V);
10639 return II;
10640 }
10641 break;
10642 }
10643
10644 case Intrinsic::ppc_altivec_vperm:
10645 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10646 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10647 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010648
Chris Lattner0521e3c2008-06-18 04:33:20 +000010649 // Check that all of the elements are integer constants or undefs.
10650 bool AllEltsOk = true;
10651 for (unsigned i = 0; i != 16; ++i) {
10652 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10653 !isa<UndefValue>(Mask->getOperand(i))) {
10654 AllEltsOk = false;
10655 break;
10656 }
10657 }
10658
10659 if (AllEltsOk) {
10660 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010661 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10662 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010663 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010664
Chris Lattner0521e3c2008-06-18 04:33:20 +000010665 // Only extract each element once.
10666 Value *ExtractedElts[32];
10667 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10668
Chris Lattnere2ed0572006-04-06 19:19:17 +000010669 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010670 if (isa<UndefValue>(Mask->getOperand(i)))
10671 continue;
10672 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10673 Idx &= 31; // Match the hardware behavior.
10674
10675 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010676 ExtractedElts[Idx] =
10677 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10678 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10679 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010680 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010681
Chris Lattner0521e3c2008-06-18 04:33:20 +000010682 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010683 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10684 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10685 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010686 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010687 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010688 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010689 }
10690 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010691
Chris Lattner0521e3c2008-06-18 04:33:20 +000010692 case Intrinsic::stackrestore: {
10693 // If the save is right next to the restore, remove the restore. This can
10694 // happen when variable allocas are DCE'd.
10695 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10696 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10697 BasicBlock::iterator BI = SS;
10698 if (&*++BI == II)
10699 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010700 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010701 }
10702
10703 // Scan down this block to see if there is another stack restore in the
10704 // same block without an intervening call/alloca.
10705 BasicBlock::iterator BI = II;
10706 TerminatorInst *TI = II->getParent()->getTerminator();
10707 bool CannotRemove = false;
10708 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010709 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010710 CannotRemove = true;
10711 break;
10712 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010713 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10714 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10715 // If there is a stackrestore below this one, remove this one.
10716 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10717 return EraseInstFromFunction(CI);
10718 // Otherwise, ignore the intrinsic.
10719 } else {
10720 // If we found a non-intrinsic call, we can't remove the stack
10721 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010722 CannotRemove = true;
10723 break;
10724 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010725 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010726 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010727
10728 // If the stack restore is in a return/unwind block and if there are no
10729 // allocas or calls between the restore and the return, nuke the restore.
10730 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10731 return EraseInstFromFunction(CI);
10732 break;
10733 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010734 }
10735
Chris Lattner8b0ea312006-01-13 20:11:04 +000010736 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010737}
10738
10739// InvokeInst simplification
10740//
10741Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010742 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010743}
10744
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010745/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10746/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010747static bool isSafeToEliminateVarargsCast(const CallSite CS,
10748 const CastInst * const CI,
10749 const TargetData * const TD,
10750 const int ix) {
10751 if (!CI->isLosslessCast())
10752 return false;
10753
10754 // The size of ByVal arguments is derived from the type, so we
10755 // can't change to a type with a different size. If the size were
10756 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010757 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010758 return true;
10759
10760 const Type* SrcTy =
10761 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10762 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10763 if (!SrcTy->isSized() || !DstTy->isSized())
10764 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010765 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010766 return false;
10767 return true;
10768}
10769
Chris Lattnera44d8a22003-10-07 22:32:43 +000010770// visitCallSite - Improvements for call and invoke instructions.
10771//
10772Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010773 bool Changed = false;
10774
10775 // If the callee is a constexpr cast of a function, attempt to move the cast
10776 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010777 if (transformConstExprCastCall(CS)) return 0;
10778
Chris Lattner6c266db2003-10-07 22:54:13 +000010779 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010780
Chris Lattner08b22ec2005-05-13 07:09:09 +000010781 if (Function *CalleeF = dyn_cast<Function>(Callee))
10782 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10783 Instruction *OldCall = CS.getInstruction();
10784 // If the call and callee calling conventions don't match, this call must
10785 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010786 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010787 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010788 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010789 // If OldCall dues not return void then replaceAllUsesWith undef.
10790 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010791 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010792 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010793 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10794 return EraseInstFromFunction(*OldCall);
10795 return 0;
10796 }
10797
Chris Lattner17be6352004-10-18 02:59:09 +000010798 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10799 // This instruction is not reachable, just remove it. We insert a store to
10800 // undef so that we know that this code is not reachable, despite the fact
10801 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010802 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010803 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010804 CS.getInstruction());
10805
Devang Patel228ebd02009-10-13 22:56:32 +000010806 // If CS dues not return void then replaceAllUsesWith undef.
10807 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010808 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010809 CS.getInstruction()->
10810 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010811
10812 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10813 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010814 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010815 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010816 }
Chris Lattner17be6352004-10-18 02:59:09 +000010817 return EraseInstFromFunction(*CS.getInstruction());
10818 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010819
Duncan Sandscdb6d922007-09-17 10:26:40 +000010820 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10821 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10822 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10823 return transformCallThroughTrampoline(CS);
10824
Chris Lattner6c266db2003-10-07 22:54:13 +000010825 const PointerType *PTy = cast<PointerType>(Callee->getType());
10826 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10827 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010828 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010829 // See if we can optimize any arguments passed through the varargs area of
10830 // the call.
10831 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010832 E = CS.arg_end(); I != E; ++I, ++ix) {
10833 CastInst *CI = dyn_cast<CastInst>(*I);
10834 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10835 *I = CI->getOperand(0);
10836 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010837 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010838 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010839 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010840
Duncan Sandsf0c33542007-12-19 21:13:37 +000010841 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010842 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010843 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010844 Changed = true;
10845 }
10846
Chris Lattner6c266db2003-10-07 22:54:13 +000010847 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010848}
10849
Chris Lattner9fe38862003-06-19 17:00:31 +000010850// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10851// attempt to move the cast to the arguments of the call/invoke.
10852//
10853bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10854 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10855 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010856 if (CE->getOpcode() != Instruction::BitCast ||
10857 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010858 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010859 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010860 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010861 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010862
10863 // Okay, this is a cast from a function to a different type. Unless doing so
10864 // would cause a type conversion of one of our arguments, change this call to
10865 // be a direct call with arguments casted to the appropriate types.
10866 //
10867 const FunctionType *FT = Callee->getFunctionType();
10868 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010869 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010870
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010871 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010872 return false; // TODO: Handle multiple return values.
10873
Chris Lattnerf78616b2004-01-14 06:06:08 +000010874 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010875 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010876 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010877 // Conversion is ok if changing from one pointer type to another or from
10878 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010879 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010880 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010881 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010882 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010883 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010884
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010885 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010886 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010887 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010888 return false; // Cannot transform this return value.
10889
Chris Lattner58d74912008-03-12 17:45:29 +000010890 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010891 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010892 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010893 return false; // Attribute not compatible with transformed value.
10894 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010895
Chris Lattnerf78616b2004-01-14 06:06:08 +000010896 // If the callsite is an invoke instruction, and the return value is used by
10897 // a PHI node in a successor, we cannot change the return type of the call
10898 // because there is no place to put the cast instruction (without breaking
10899 // the critical edge). Bail out in this case.
10900 if (!Caller->use_empty())
10901 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10902 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10903 UI != E; ++UI)
10904 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10905 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010906 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010907 return false;
10908 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010909
10910 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10911 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010912
Chris Lattner9fe38862003-06-19 17:00:31 +000010913 CallSite::arg_iterator AI = CS.arg_begin();
10914 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10915 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010916 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010917
10918 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010919 return false; // Cannot transform this parameter value.
10920
Devang Patel19c87462008-09-26 22:53:05 +000010921 if (CallerPAL.getParamAttributes(i + 1)
10922 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010923 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010924
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010925 // Converting from one pointer type to another or between a pointer and an
10926 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010927 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010928 (TD && ((isa<PointerType>(ParamTy) ||
10929 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10930 (isa<PointerType>(ActTy) ||
10931 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010932 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010933 }
10934
10935 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010936 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010937 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010938
Chris Lattner58d74912008-03-12 17:45:29 +000010939 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10940 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010941 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010942 // won't be dropping them. Check that these extra arguments have attributes
10943 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010944 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10945 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010946 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010947 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010948 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010949 return false;
10950 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010951
Chris Lattner9fe38862003-06-19 17:00:31 +000010952 // Okay, we decided that this is a safe thing to do: go ahead and start
10953 // inserting cast instructions as necessary...
10954 std::vector<Value*> Args;
10955 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010956 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010957 attrVec.reserve(NumCommonArgs);
10958
10959 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010960 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010961
10962 // If the return value is not being used, the type may not be compatible
10963 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010964 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010965
10966 // Add the new return attributes.
10967 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010968 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010969
10970 AI = CS.arg_begin();
10971 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10972 const Type *ParamTy = FT->getParamType(i);
10973 if ((*AI)->getType() == ParamTy) {
10974 Args.push_back(*AI);
10975 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010976 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010977 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010978 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010979 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010980
10981 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010982 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010983 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010984 }
10985
10986 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010987 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010988 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010989 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010990
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010991 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010992 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010993 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010994 errs() << "WARNING: While resolving call to function '"
10995 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010996 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010997 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010998 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10999 const Type *PTy = getPromotedType((*AI)->getType());
11000 if (PTy != (*AI)->getType()) {
11001 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011002 Instruction::CastOps opcode =
11003 CastInst::getCastOpcode(*AI, false, PTy, false);
11004 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000011005 } else {
11006 Args.push_back(*AI);
11007 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000011008
Duncan Sandse1e520f2008-01-13 08:02:44 +000011009 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000011010 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000011011 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000011012 }
Chris Lattner9fe38862003-06-19 17:00:31 +000011013 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011014 }
Chris Lattner9fe38862003-06-19 17:00:31 +000011015
Devang Patel19c87462008-09-26 22:53:05 +000011016 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
11017 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
11018
Devang Patel9674d152009-10-14 17:29:00 +000011019 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000011020 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000011021
Eric Christophera66297a2009-07-25 02:45:27 +000011022 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
11023 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000011024
Chris Lattner9fe38862003-06-19 17:00:31 +000011025 Instruction *NC;
11026 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011027 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011028 Args.begin(), Args.end(),
11029 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000011030 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011031 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000011032 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011033 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
11034 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000011035 CallInst *CI = cast<CallInst>(Caller);
11036 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000011037 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000011038 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011039 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000011040 }
11041
Chris Lattner6934a042007-02-11 01:23:03 +000011042 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000011043 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011044 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000011045 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011046 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011047 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011048 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000011049
11050 // If this is an invoke instruction, we should insert it after the first
11051 // non-phi, instruction in the normal successor block.
11052 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000011053 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000011054 InsertNewInstBefore(NC, *I);
11055 } else {
11056 // Otherwise, it's a call, just insert cast right after the call instr
11057 InsertNewInstBefore(NC, *Caller);
11058 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000011059 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011060 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011061 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000011062 }
11063 }
11064
Devang Patel1bf5ebc2009-10-13 21:41:20 +000011065
Chris Lattner931f8f32009-08-31 05:17:58 +000011066 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000011067 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000011068
11069 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011070 return true;
11071}
11072
Duncan Sandscdb6d922007-09-17 10:26:40 +000011073// transformCallThroughTrampoline - Turn a call to a function created by the
11074// init_trampoline intrinsic into a direct call to the underlying function.
11075//
11076Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
11077 Value *Callee = CS.getCalledValue();
11078 const PointerType *PTy = cast<PointerType>(Callee->getType());
11079 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000011080 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011081
11082 // If the call already has the 'nest' attribute somewhere then give up -
11083 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000011084 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011085 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011086
11087 IntrinsicInst *Tramp =
11088 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
11089
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000011090 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011091 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
11092 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
11093
Devang Patel05988662008-09-25 21:00:45 +000011094 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000011095 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011096 unsigned NestIdx = 1;
11097 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000011098 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011099
11100 // Look for a parameter marked with the 'nest' attribute.
11101 for (FunctionType::param_iterator I = NestFTy->param_begin(),
11102 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000011103 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011104 // Record the parameter type and any other attributes.
11105 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000011106 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011107 break;
11108 }
11109
11110 if (NestTy) {
11111 Instruction *Caller = CS.getInstruction();
11112 std::vector<Value*> NewArgs;
11113 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11114
Devang Patel05988662008-09-25 21:00:45 +000011115 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000011116 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011117
Duncan Sandscdb6d922007-09-17 10:26:40 +000011118 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011119 // mean appending it. Likewise for attributes.
11120
Devang Patel19c87462008-09-26 22:53:05 +000011121 // Add any result attributes.
11122 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000011123 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011124
Duncan Sandscdb6d922007-09-17 10:26:40 +000011125 {
11126 unsigned Idx = 1;
11127 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11128 do {
11129 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011130 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011131 Value *NestVal = Tramp->getOperand(3);
11132 if (NestVal->getType() != NestTy)
11133 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11134 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000011135 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011136 }
11137
11138 if (I == E)
11139 break;
11140
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011141 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011142 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000011143 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011144 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000011145 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011146
11147 ++Idx, ++I;
11148 } while (1);
11149 }
11150
Devang Patel19c87462008-09-26 22:53:05 +000011151 // Add any function attributes.
11152 if (Attributes Attr = Attrs.getFnAttributes())
11153 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11154
Duncan Sandscdb6d922007-09-17 10:26:40 +000011155 // The trampoline may have been bitcast to a bogus type (FTy).
11156 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011157 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011158
Duncan Sandscdb6d922007-09-17 10:26:40 +000011159 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011160 NewTypes.reserve(FTy->getNumParams()+1);
11161
Duncan Sandscdb6d922007-09-17 10:26:40 +000011162 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011163 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011164 {
11165 unsigned Idx = 1;
11166 FunctionType::param_iterator I = FTy->param_begin(),
11167 E = FTy->param_end();
11168
11169 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011170 if (Idx == NestIdx)
11171 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011172 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011173
11174 if (I == E)
11175 break;
11176
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011177 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011178 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011179
11180 ++Idx, ++I;
11181 } while (1);
11182 }
11183
11184 // Replace the trampoline call with a direct call. Let the generic
11185 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000011186 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000011187 FTy->isVarArg());
11188 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000011189 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000011190 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000011191 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000011192 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11193 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011194
11195 Instruction *NewCaller;
11196 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011197 NewCaller = InvokeInst::Create(NewCallee,
11198 II->getNormalDest(), II->getUnwindDest(),
11199 NewArgs.begin(), NewArgs.end(),
11200 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011201 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011202 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011203 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011204 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11205 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011206 if (cast<CallInst>(Caller)->isTailCall())
11207 cast<CallInst>(NewCaller)->setTailCall();
11208 cast<CallInst>(NewCaller)->
11209 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011210 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011211 }
Devang Patel9674d152009-10-14 17:29:00 +000011212 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000011213 Caller->replaceAllUsesWith(NewCaller);
11214 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000011215 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011216 return 0;
11217 }
11218 }
11219
11220 // Replace the trampoline call with a direct call. Since there is no 'nest'
11221 // parameter, there is no need to adjust the argument list. Let the generic
11222 // code sort out any function type mismatches.
11223 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000011224 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000011225 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011226 CS.setCalledFunction(NewCallee);
11227 return CS.getInstruction();
11228}
11229
Dan Gohman9ad29202009-09-16 16:50:24 +000011230/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11231/// 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 +000011232/// and a single binop.
11233Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11234 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011235 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000011236 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011237 Value *LHSVal = FirstInst->getOperand(0);
11238 Value *RHSVal = FirstInst->getOperand(1);
11239
11240 const Type *LHSType = LHSVal->getType();
11241 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000011242
Dan Gohman9ad29202009-09-16 16:50:24 +000011243 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011244 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000011245 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000011246 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000011247 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000011248 // types or GEP's with different index types.
11249 I->getOperand(0)->getType() != LHSType ||
11250 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000011251 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011252
11253 // If they are CmpInst instructions, check their predicates
11254 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11255 if (cast<CmpInst>(I)->getPredicate() !=
11256 cast<CmpInst>(FirstInst)->getPredicate())
11257 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011258
11259 // Keep track of which operand needs a phi node.
11260 if (I->getOperand(0) != LHSVal) LHSVal = 0;
11261 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011262 }
Dan Gohman9ad29202009-09-16 16:50:24 +000011263
11264 // If both LHS and RHS would need a PHI, don't do this transformation,
11265 // because it would increase the number of PHIs entering the block,
11266 // which leads to higher register pressure. This is especially
11267 // bad when the PHIs are in the header of a loop.
11268 if (!LHSVal && !RHSVal)
11269 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011270
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011271 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000011272
Chris Lattner7da52b22006-11-01 04:51:18 +000011273 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000011274 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000011275 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011276 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011277 NewLHS = PHINode::Create(LHSType,
11278 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011279 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11280 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011281 InsertNewInstBefore(NewLHS, PN);
11282 LHSVal = NewLHS;
11283 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011284
11285 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011286 NewRHS = PHINode::Create(RHSType,
11287 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011288 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11289 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011290 InsertNewInstBefore(NewRHS, PN);
11291 RHSVal = NewRHS;
11292 }
11293
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011294 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000011295 if (NewLHS || NewRHS) {
11296 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11297 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11298 if (NewLHS) {
11299 Value *NewInLHS = InInst->getOperand(0);
11300 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11301 }
11302 if (NewRHS) {
11303 Value *NewInRHS = InInst->getOperand(1);
11304 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11305 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011306 }
11307 }
11308
Chris Lattner7da52b22006-11-01 04:51:18 +000011309 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011310 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011311 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000011312 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000011313 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000011314}
11315
Chris Lattner05f18922008-12-01 02:34:36 +000011316Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11317 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11318
11319 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11320 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011321 // This is true if all GEP bases are allocas and if all indices into them are
11322 // constants.
11323 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011324
11325 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011326 // more than one phi, which leads to higher register pressure. This is
11327 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011328 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011329
Dan Gohman9ad29202009-09-16 16:50:24 +000011330 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011331 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11332 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11333 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11334 GEP->getNumOperands() != FirstInst->getNumOperands())
11335 return 0;
11336
Chris Lattner36d3e322009-02-21 00:46:50 +000011337 // Keep track of whether or not all GEPs are of alloca pointers.
11338 if (AllBasePointersAreAllocas &&
11339 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11340 !GEP->hasAllConstantIndices()))
11341 AllBasePointersAreAllocas = false;
11342
Chris Lattner05f18922008-12-01 02:34:36 +000011343 // Compare the operand lists.
11344 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11345 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11346 continue;
11347
11348 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11349 // if one of the PHIs has a constant for the index. The index may be
11350 // substantially cheaper to compute for the constants, so making it a
11351 // variable index could pessimize the path. This also handles the case
11352 // for struct indices, which must always be constant.
11353 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11354 isa<ConstantInt>(GEP->getOperand(op)))
11355 return 0;
11356
11357 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11358 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011359
11360 // If we already needed a PHI for an earlier operand, and another operand
11361 // also requires a PHI, we'd be introducing more PHIs than we're
11362 // eliminating, which increases register pressure on entry to the PHI's
11363 // block.
11364 if (NeededPhi)
11365 return 0;
11366
Chris Lattner05f18922008-12-01 02:34:36 +000011367 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011368 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011369 }
11370 }
11371
Chris Lattner36d3e322009-02-21 00:46:50 +000011372 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011373 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011374 // offset calculation, but all the predecessors will have to materialize the
11375 // stack address into a register anyway. We'd actually rather *clone* the
11376 // load up into the predecessors so that we have a load of a gep of an alloca,
11377 // which can usually all be folded into the load.
11378 if (AllBasePointersAreAllocas)
11379 return 0;
11380
Chris Lattner05f18922008-12-01 02:34:36 +000011381 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11382 // that is variable.
11383 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11384
11385 bool HasAnyPHIs = false;
11386 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11387 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11388 Value *FirstOp = FirstInst->getOperand(i);
11389 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11390 FirstOp->getName()+".pn");
11391 InsertNewInstBefore(NewPN, PN);
11392
11393 NewPN->reserveOperandSpace(e);
11394 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11395 OperandPhis[i] = NewPN;
11396 FixedOperands[i] = NewPN;
11397 HasAnyPHIs = true;
11398 }
11399
11400
11401 // Add all operands to the new PHIs.
11402 if (HasAnyPHIs) {
11403 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11404 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11405 BasicBlock *InBB = PN.getIncomingBlock(i);
11406
11407 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11408 if (PHINode *OpPhi = OperandPhis[op])
11409 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11410 }
11411 }
11412
11413 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011414 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11415 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11416 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011417 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11418 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011419}
11420
11421
Chris Lattner21550882009-02-23 05:56:17 +000011422/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11423/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011424/// obvious the value of the load is not changed from the point of the load to
11425/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011426///
11427/// Finally, it is safe, but not profitable, to sink a load targetting a
11428/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11429/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011430static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011431 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11432
11433 for (++BBI; BBI != E; ++BBI)
11434 if (BBI->mayWriteToMemory())
11435 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011436
11437 // Check for non-address taken alloca. If not address-taken already, it isn't
11438 // profitable to do this xform.
11439 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11440 bool isAddressTaken = false;
11441 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11442 UI != E; ++UI) {
11443 if (isa<LoadInst>(UI)) continue;
11444 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11445 // If storing TO the alloca, then the address isn't taken.
11446 if (SI->getOperand(1) == AI) continue;
11447 }
11448 isAddressTaken = true;
11449 break;
11450 }
11451
Chris Lattner36d3e322009-02-21 00:46:50 +000011452 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011453 return false;
11454 }
11455
Chris Lattner36d3e322009-02-21 00:46:50 +000011456 // If this load is a load from a GEP with a constant offset from an alloca,
11457 // then we don't want to sink it. In its present form, it will be
11458 // load [constant stack offset]. Sinking it will cause us to have to
11459 // materialize the stack addresses in each predecessor in a register only to
11460 // do a shared load from register in the successor.
11461 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11462 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11463 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11464 return false;
11465
Chris Lattner76c73142006-11-01 07:13:54 +000011466 return true;
11467}
11468
Chris Lattner751a3622009-11-01 20:04:24 +000011469Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11470 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11471
11472 // When processing loads, we need to propagate two bits of information to the
11473 // sunk load: whether it is volatile, and what its alignment is. We currently
11474 // don't sink loads when some have their alignment specified and some don't.
11475 // visitLoadInst will propagate an alignment onto the load when TD is around,
11476 // and if TD isn't around, we can't handle the mixed case.
11477 bool isVolatile = FirstLI->isVolatile();
11478 unsigned LoadAlignment = FirstLI->getAlignment();
11479
11480 // We can't sink the load if the loaded value could be modified between the
11481 // load and the PHI.
11482 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11483 !isSafeAndProfitableToSinkLoad(FirstLI))
11484 return 0;
11485
11486 // If the PHI is of volatile loads and the load block has multiple
11487 // successors, sinking it would remove a load of the volatile value from
11488 // the path through the other successor.
11489 if (isVolatile &&
11490 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11491 return 0;
11492
11493 // Check to see if all arguments are the same operation.
11494 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11495 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11496 if (!LI || !LI->hasOneUse())
11497 return 0;
11498
11499 // We can't sink the load if the loaded value could be modified between
11500 // the load and the PHI.
11501 if (LI->isVolatile() != isVolatile ||
11502 LI->getParent() != PN.getIncomingBlock(i) ||
11503 !isSafeAndProfitableToSinkLoad(LI))
11504 return 0;
11505
11506 // If some of the loads have an alignment specified but not all of them,
11507 // we can't do the transformation.
11508 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11509 return 0;
11510
Chris Lattnera664bb72009-11-01 20:07:07 +000011511 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011512
11513 // If the PHI is of volatile loads and the load block has multiple
11514 // successors, sinking it would remove a load of the volatile value from
11515 // the path through the other successor.
11516 if (isVolatile &&
11517 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11518 return 0;
11519 }
11520
11521 // Okay, they are all the same operation. Create a new PHI node of the
11522 // correct type, and PHI together all of the LHS's of the instructions.
11523 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11524 PN.getName()+".in");
11525 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11526
11527 Value *InVal = FirstLI->getOperand(0);
11528 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11529
11530 // Add all operands to the new PHI.
11531 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11532 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11533 if (NewInVal != InVal)
11534 InVal = 0;
11535 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11536 }
11537
11538 Value *PhiVal;
11539 if (InVal) {
11540 // The new PHI unions all of the same values together. This is really
11541 // common, so we handle it intelligently here for compile-time speed.
11542 PhiVal = InVal;
11543 delete NewPN;
11544 } else {
11545 InsertNewInstBefore(NewPN, PN);
11546 PhiVal = NewPN;
11547 }
11548
11549 // If this was a volatile load that we are merging, make sure to loop through
11550 // and mark all the input loads as non-volatile. If we don't do this, we will
11551 // insert a new volatile load and the old ones will not be deletable.
11552 if (isVolatile)
11553 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11554 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11555
11556 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11557}
11558
Chris Lattner9fe38862003-06-19 17:00:31 +000011559
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011560
11561/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11562/// operator and they all are only used by the PHI, PHI together their
11563/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011564Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11565 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11566
Chris Lattner751a3622009-11-01 20:04:24 +000011567 if (isa<GetElementPtrInst>(FirstInst))
11568 return FoldPHIArgGEPIntoPHI(PN);
11569 if (isa<LoadInst>(FirstInst))
11570 return FoldPHIArgLoadIntoPHI(PN);
11571
Chris Lattnerbac32862004-11-14 19:13:23 +000011572 // Scan the instruction, looking for input operations that can be folded away.
11573 // If all input operands to the phi are the same instruction (e.g. a cast from
11574 // the same type or "+42") we can pull the operation through the PHI, reducing
11575 // code size and simplifying code.
11576 Constant *ConstantOp = 0;
11577 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011578
Chris Lattnerbac32862004-11-14 19:13:23 +000011579 if (isa<CastInst>(FirstInst)) {
11580 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011581
11582 // Be careful about transforming integer PHIs. We don't want to pessimize
11583 // the code by turning an i32 into an i1293.
11584 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011585 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011586 return 0;
11587 }
Reid Spencer832254e2007-02-02 02:16:23 +000011588 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011589 // Can fold binop, compare or shift here if the RHS is a constant,
11590 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011591 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011592 if (ConstantOp == 0)
11593 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011594 } else {
11595 return 0; // Cannot fold this operation.
11596 }
11597
11598 // Check to see if all arguments are the same operation.
11599 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011600 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11601 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011602 return 0;
11603 if (CastSrcTy) {
11604 if (I->getOperand(0)->getType() != CastSrcTy)
11605 return 0; // Cast operation must match.
11606 } else if (I->getOperand(1) != ConstantOp) {
11607 return 0;
11608 }
11609 }
11610
11611 // Okay, they are all the same operation. Create a new PHI node of the
11612 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011613 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11614 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011615 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011616
11617 Value *InVal = FirstInst->getOperand(0);
11618 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011619
11620 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011621 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11622 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11623 if (NewInVal != InVal)
11624 InVal = 0;
11625 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11626 }
11627
11628 Value *PhiVal;
11629 if (InVal) {
11630 // The new PHI unions all of the same values together. This is really
11631 // common, so we handle it intelligently here for compile-time speed.
11632 PhiVal = InVal;
11633 delete NewPN;
11634 } else {
11635 InsertNewInstBefore(NewPN, PN);
11636 PhiVal = NewPN;
11637 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011638
Chris Lattnerbac32862004-11-14 19:13:23 +000011639 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011640 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011641 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011642
Chris Lattner54545ac2008-04-29 17:13:43 +000011643 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011644 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011645
Chris Lattner751a3622009-11-01 20:04:24 +000011646 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11647 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11648 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011649}
Chris Lattnera1be5662002-05-02 17:06:02 +000011650
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011651/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11652/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011653static bool DeadPHICycle(PHINode *PN,
11654 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011655 if (PN->use_empty()) return true;
11656 if (!PN->hasOneUse()) return false;
11657
11658 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011659 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011660 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011661
11662 // Don't scan crazily complex things.
11663 if (PotentiallyDeadPHIs.size() == 16)
11664 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011665
11666 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11667 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011668
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011669 return false;
11670}
11671
Chris Lattnercf5008a2007-11-06 21:52:06 +000011672/// PHIsEqualValue - Return true if this phi node is always equal to
11673/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11674/// z = some value; x = phi (y, z); y = phi (x, z)
11675static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11676 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11677 // See if we already saw this PHI node.
11678 if (!ValueEqualPHIs.insert(PN))
11679 return true;
11680
11681 // Don't scan crazily complex things.
11682 if (ValueEqualPHIs.size() == 16)
11683 return false;
11684
11685 // Scan the operands to see if they are either phi nodes or are equal to
11686 // the value.
11687 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11688 Value *Op = PN->getIncomingValue(i);
11689 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11690 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11691 return false;
11692 } else if (Op != NonPhiInVal)
11693 return false;
11694 }
11695
11696 return true;
11697}
11698
11699
Chris Lattner9956c052009-11-08 19:23:30 +000011700namespace {
11701struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011702 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011703 unsigned Shift; // The amount shifted.
11704 Instruction *Inst; // The trunc instruction.
11705
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011706 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11707 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011708
11709 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011710 if (PHIId < RHS.PHIId) return true;
11711 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011712 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011713 if (Shift > RHS.Shift) return false;
11714 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011715 RHS.Inst->getType()->getPrimitiveSizeInBits();
11716 }
11717};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011718
11719struct LoweredPHIRecord {
11720 PHINode *PN; // The PHI that was lowered.
11721 unsigned Shift; // The amount shifted.
11722 unsigned Width; // The width extracted.
11723
11724 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11725 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11726
11727 // Ctor form used by DenseMap.
11728 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11729 : PN(pn), Shift(Sh), Width(0) {}
11730};
11731}
11732
11733namespace llvm {
11734 template<>
11735 struct DenseMapInfo<LoweredPHIRecord> {
11736 static inline LoweredPHIRecord getEmptyKey() {
11737 return LoweredPHIRecord(0, 0);
11738 }
11739 static inline LoweredPHIRecord getTombstoneKey() {
11740 return LoweredPHIRecord(0, 1);
11741 }
11742 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11743 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11744 (Val.Width>>3);
11745 }
11746 static bool isEqual(const LoweredPHIRecord &LHS,
11747 const LoweredPHIRecord &RHS) {
11748 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11749 LHS.Width == RHS.Width;
11750 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011751 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011752 template <>
11753 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011754}
11755
11756
11757/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11758/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11759/// so, we split the PHI into the various pieces being extracted. This sort of
11760/// thing is introduced when SROA promotes an aggregate to large integer values.
11761///
11762/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11763/// inttoptr. We should produce new PHIs in the right type.
11764///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011765Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11766 // PHIUsers - Keep track of all of the truncated values extracted from a set
11767 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011768 SmallVector<PHIUsageRecord, 16> PHIUsers;
11769
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011770 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11771 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11772 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11773 // check the uses of (to ensure they are all extracts).
11774 SmallVector<PHINode*, 8> PHIsToSlice;
11775 SmallPtrSet<PHINode*, 8> PHIsInspected;
11776
11777 PHIsToSlice.push_back(&FirstPhi);
11778 PHIsInspected.insert(&FirstPhi);
11779
11780 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11781 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011782
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011783 // Scan the input list of the PHI. If any input is an invoke, and if the
11784 // input is defined in the predecessor, then we won't be split the critical
11785 // edge which is required to insert a truncate. Because of this, we have to
11786 // bail out.
11787 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11788 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11789 if (II == 0) continue;
11790 if (II->getParent() != PN->getIncomingBlock(i))
11791 continue;
11792
11793 // If we have a phi, and if it's directly in the predecessor, then we have
11794 // a critical edge where we need to put the truncate. Since we can't
11795 // split the edge in instcombine, we have to bail out.
11796 return 0;
11797 }
11798
11799
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011800 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11801 UI != E; ++UI) {
11802 Instruction *User = cast<Instruction>(*UI);
11803
11804 // If the user is a PHI, inspect its uses recursively.
11805 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11806 if (PHIsInspected.insert(UserPN))
11807 PHIsToSlice.push_back(UserPN);
11808 continue;
11809 }
11810
11811 // Truncates are always ok.
11812 if (isa<TruncInst>(User)) {
11813 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11814 continue;
11815 }
11816
11817 // Otherwise it must be a lshr which can only be used by one trunc.
11818 if (User->getOpcode() != Instruction::LShr ||
11819 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11820 !isa<ConstantInt>(User->getOperand(1)))
11821 return 0;
11822
11823 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11824 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011825 }
Chris Lattner9956c052009-11-08 19:23:30 +000011826 }
11827
11828 // If we have no users, they must be all self uses, just nuke the PHI.
11829 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011830 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011831
11832 // If this phi node is transformable, create new PHIs for all the pieces
11833 // extracted out of it. First, sort the users by their offset and size.
11834 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11835
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011836 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11837 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11838 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11839 );
Chris Lattner9956c052009-11-08 19:23:30 +000011840
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011841 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11842 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011843 DenseMap<BasicBlock*, Value*> PredValues;
11844
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011845 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11846 // introduce redundant PHIs.
11847 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11848
11849 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11850 unsigned PHIId = PHIUsers[UserI].PHIId;
11851 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011852 unsigned Offset = PHIUsers[UserI].Shift;
11853 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011854
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011855 PHINode *EltPHI;
11856
11857 // If we've already lowered a user like this, reuse the previously lowered
11858 // value.
11859 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011860
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011861 // Otherwise, Create the new PHI node for this user.
11862 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11863 assert(EltPHI->getType() != PN->getType() &&
11864 "Truncate didn't shrink phi?");
11865
11866 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11867 BasicBlock *Pred = PN->getIncomingBlock(i);
11868 Value *&PredVal = PredValues[Pred];
11869
11870 // If we already have a value for this predecessor, reuse it.
11871 if (PredVal) {
11872 EltPHI->addIncoming(PredVal, Pred);
11873 continue;
11874 }
Chris Lattner9956c052009-11-08 19:23:30 +000011875
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011876 // Handle the PHI self-reuse case.
11877 Value *InVal = PN->getIncomingValue(i);
11878 if (InVal == PN) {
11879 PredVal = EltPHI;
11880 EltPHI->addIncoming(PredVal, Pred);
11881 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011882 }
11883
11884 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011885 // If the incoming value was a PHI, and if it was one of the PHIs we
11886 // already rewrote it, just use the lowered value.
11887 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11888 PredVal = Res;
11889 EltPHI->addIncoming(PredVal, Pred);
11890 continue;
11891 }
11892 }
11893
11894 // Otherwise, do an extract in the predecessor.
11895 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11896 Value *Res = InVal;
11897 if (Offset)
11898 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11899 Offset), "extract");
11900 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11901 PredVal = Res;
11902 EltPHI->addIncoming(Res, Pred);
11903
11904 // If the incoming value was a PHI, and if it was one of the PHIs we are
11905 // rewriting, we will ultimately delete the code we inserted. This
11906 // means we need to revisit that PHI to make sure we extract out the
11907 // needed piece.
11908 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11909 if (PHIsInspected.count(OldInVal)) {
11910 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11911 OldInVal)-PHIsToSlice.begin();
11912 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11913 cast<Instruction>(Res)));
11914 ++UserE;
11915 }
Chris Lattner9956c052009-11-08 19:23:30 +000011916 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011917 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011918
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011919 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11920 << *EltPHI << '\n');
11921 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011922 }
Chris Lattner9956c052009-11-08 19:23:30 +000011923
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011924 // Replace the use of this piece with the PHI node.
11925 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011926 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011927
11928 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11929 // with undefs.
11930 Value *Undef = UndefValue::get(FirstPhi.getType());
11931 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11932 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11933 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011934}
11935
Chris Lattner473945d2002-05-06 18:06:38 +000011936// PHINode simplification
11937//
Chris Lattner7e708292002-06-25 16:13:24 +000011938Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011939 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011940 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011941
Owen Anderson7e057142006-07-10 22:03:18 +000011942 if (Value *V = PN.hasConstantValue())
11943 return ReplaceInstUsesWith(PN, V);
11944
Owen Anderson7e057142006-07-10 22:03:18 +000011945 // If all PHI operands are the same operation, pull them through the PHI,
11946 // reducing code size.
11947 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011948 isa<Instruction>(PN.getIncomingValue(1)) &&
11949 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11950 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11951 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11952 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011953 PN.getIncomingValue(0)->hasOneUse())
11954 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11955 return Result;
11956
11957 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11958 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11959 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011960 if (PN.hasOneUse()) {
11961 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11962 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011963 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011964 PotentiallyDeadPHIs.insert(&PN);
11965 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011966 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011967 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011968
11969 // If this phi has a single use, and if that use just computes a value for
11970 // the next iteration of a loop, delete the phi. This occurs with unused
11971 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11972 // common case here is good because the only other things that catch this
11973 // are induction variable analysis (sometimes) and ADCE, which is only run
11974 // late.
11975 if (PHIUser->hasOneUse() &&
11976 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11977 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011978 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011979 }
11980 }
Owen Anderson7e057142006-07-10 22:03:18 +000011981
Chris Lattnercf5008a2007-11-06 21:52:06 +000011982 // We sometimes end up with phi cycles that non-obviously end up being the
11983 // same value, for example:
11984 // z = some value; x = phi (y, z); y = phi (x, z)
11985 // where the phi nodes don't necessarily need to be in the same block. Do a
11986 // quick check to see if the PHI node only contains a single non-phi value, if
11987 // so, scan to see if the phi cycle is actually equal to that value.
11988 {
11989 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11990 // Scan for the first non-phi operand.
11991 while (InValNo != NumOperandVals &&
11992 isa<PHINode>(PN.getIncomingValue(InValNo)))
11993 ++InValNo;
11994
11995 if (InValNo != NumOperandVals) {
11996 Value *NonPhiInVal = PN.getOperand(InValNo);
11997
11998 // Scan the rest of the operands to see if there are any conflicts, if so
11999 // there is no need to recursively scan other phis.
12000 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
12001 Value *OpVal = PN.getIncomingValue(InValNo);
12002 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
12003 break;
12004 }
12005
12006 // If we scanned over all operands, then we have one unique value plus
12007 // phi values. Scan PHI nodes to see if they all merge in each other or
12008 // the value.
12009 if (InValNo == NumOperandVals) {
12010 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
12011 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
12012 return ReplaceInstUsesWith(PN, NonPhiInVal);
12013 }
12014 }
12015 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000012016
Dan Gohman5b097012009-10-31 14:22:52 +000012017 // If there are multiple PHIs, sort their operands so that they all list
12018 // the blocks in the same order. This will help identical PHIs be eliminated
12019 // by other passes. Other passes shouldn't depend on this for correctness
12020 // however.
12021 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
12022 if (&PN != FirstPN)
12023 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000012024 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000012025 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
12026 if (BBA != BBB) {
12027 Value *VA = PN.getIncomingValue(i);
12028 unsigned j = PN.getBasicBlockIndex(BBB);
12029 Value *VB = PN.getIncomingValue(j);
12030 PN.setIncomingBlock(i, BBB);
12031 PN.setIncomingValue(i, VB);
12032 PN.setIncomingBlock(j, BBA);
12033 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000012034 // NOTE: Instcombine normally would want us to "return &PN" if we
12035 // modified any of the operands of an instruction. However, since we
12036 // aren't adding or removing uses (just rearranging them) we don't do
12037 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000012038 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000012039 }
12040
Chris Lattner9956c052009-11-08 19:23:30 +000012041 // If this is an integer PHI and we know that it has an illegal type, see if
12042 // it is only used by trunc or trunc(lshr) operations. If so, we split the
12043 // PHI into the various pieces being extracted. This sort of thing is
12044 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000012045 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000012046 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
12047 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
12048 return Res;
12049
Chris Lattner60921c92003-12-19 05:58:40 +000012050 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000012051}
12052
Chris Lattner7e708292002-06-25 16:13:24 +000012053Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012054 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
12055
12056 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
12057 return ReplaceInstUsesWith(GEP, V);
12058
Chris Lattner620ce142004-05-07 22:09:22 +000012059 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012060
Chris Lattnere87597f2004-10-16 18:11:37 +000012061 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012062 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012063
Chris Lattner28977af2004-04-05 01:30:19 +000012064 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000012065 if (TD) {
12066 bool MadeChange = false;
12067 unsigned PtrSize = TD->getPointerSizeInBits();
12068
12069 gep_type_iterator GTI = gep_type_begin(GEP);
12070 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
12071 I != E; ++I, ++GTI) {
12072 if (!isa<SequentialType>(*GTI)) continue;
12073
Chris Lattnercb69a4e2004-04-07 18:38:20 +000012074 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000012075 // to what we need. If narrower, sign-extend it to what we need. This
12076 // explicit cast can make subsequent optimizations more obvious.
12077 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000012078 if (OpBits == PtrSize)
12079 continue;
12080
Chris Lattner2345d1d2009-08-30 20:01:10 +000012081 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012082 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000012083 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000012084 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000012085 }
Chris Lattner28977af2004-04-05 01:30:19 +000012086
Chris Lattner90ac28c2002-08-02 19:29:35 +000012087 // Combine Indices - If the source pointer to this getelementptr instruction
12088 // is a getelementptr instruction, combine the indices of the two
12089 // getelementptr instructions into a single instruction.
12090 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012091 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000012092 // Note that if our source is a gep chain itself that we wait for that
12093 // chain to be resolved before we perform this transformation. This
12094 // avoids us creating a TON of code in some cases.
12095 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012096 if (GetElementPtrInst *SrcGEP =
12097 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
12098 if (SrcGEP->getNumOperands() == 2)
12099 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000012100
Chris Lattner72588fc2007-02-15 22:48:32 +000012101 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000012102
12103 // Find out whether the last index in the source GEP is a sequential idx.
12104 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000012105 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12106 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000012107 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012108
Chris Lattner90ac28c2002-08-02 19:29:35 +000012109 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000012110 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000012111 // Replace: gep (gep %P, long B), long A, ...
12112 // With: T = long A+B; gep %P, T, ...
12113 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012114 Value *Sum;
12115 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12116 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000012117 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012118 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000012119 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012120 Sum = SO1;
12121 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000012122 // If they aren't the same type, then the input hasn't been processed
12123 // by the loop above yet (which canonicalizes sequential index types to
12124 // intptr_t). Just avoid transforming this until the input has been
12125 // normalized.
12126 if (SO1->getType() != GO1->getType())
12127 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012128 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000012129 }
Chris Lattner620ce142004-05-07 22:09:22 +000012130
Chris Lattnerab984842009-08-30 05:30:55 +000012131 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012132 if (Src->getNumOperands() == 2) {
12133 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000012134 GEP.setOperand(1, Sum);
12135 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000012136 }
Chris Lattnerab984842009-08-30 05:30:55 +000012137 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012138 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000012139 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000012140 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000012141 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012142 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000012143 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000012144 Indices.append(Src->op_begin()+1, Src->op_end());
12145 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000012146 }
12147
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012148 if (!Indices.empty())
12149 return (cast<GEPOperator>(&GEP)->isInBounds() &&
12150 Src->isInBounds()) ?
12151 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12152 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012153 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000012154 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000012155 }
12156
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012157 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12158 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000012159 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000012160
Chris Lattner2de23192009-08-30 20:38:21 +000012161 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
12162 // want to change the gep until the bitcasts are eliminated.
12163 if (getBitCastOperand(X)) {
12164 Worklist.AddValue(PtrOp);
12165 return 0;
12166 }
12167
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012168 bool HasZeroPointerIndex = false;
12169 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12170 HasZeroPointerIndex = C->isZero();
12171
Chris Lattner963f4ba2009-08-30 20:36:46 +000012172 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12173 // into : GEP [10 x i8]* X, i32 0, ...
12174 //
12175 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12176 // into : GEP i8* X, ...
12177 //
12178 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000012179 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000012180 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12181 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012182 if (const ArrayType *CATy =
12183 dyn_cast<ArrayType>(CPTy->getElementType())) {
12184 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12185 if (CATy->getElementType() == XTy->getElementType()) {
12186 // -> GEP i8* X, ...
12187 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012188 return cast<GEPOperator>(&GEP)->isInBounds() ?
12189 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12190 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012191 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12192 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000012193 }
12194
12195 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012196 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000012197 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012198 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000012199 // At this point, we know that the cast source type is a pointer
12200 // to an array of the same type as the destination pointer
12201 // array. Because the array type is never stepped over (there
12202 // is a leading zero) we can fold the cast into this GEP.
12203 GEP.setOperand(0, X);
12204 return &GEP;
12205 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012206 }
12207 }
Chris Lattnereed48272005-09-13 00:40:14 +000012208 } else if (GEP.getNumOperands() == 2) {
12209 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012210 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12211 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000012212 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12213 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012214 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000012215 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12216 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000012217 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012218 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012219 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012220 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12221 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012222 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012223 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012224 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012225 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000012226
12227 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012228 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000012229 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012230 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000012231
Owen Anderson1d0be152009-08-13 21:58:54 +000012232 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000012233 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000012234 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012235
12236 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
12237 // allow either a mul, shift, or constant here.
12238 Value *NewIdx = 0;
12239 ConstantInt *Scale = 0;
12240 if (ArrayEltSize == 1) {
12241 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000012242 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012243 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012244 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012245 Scale = CI;
12246 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12247 if (Inst->getOpcode() == Instruction::Shl &&
12248 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000012249 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12250 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000012251 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000012252 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012253 NewIdx = Inst->getOperand(0);
12254 } else if (Inst->getOpcode() == Instruction::Mul &&
12255 isa<ConstantInt>(Inst->getOperand(1))) {
12256 Scale = cast<ConstantInt>(Inst->getOperand(1));
12257 NewIdx = Inst->getOperand(0);
12258 }
12259 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012260
Chris Lattner7835cdd2005-09-13 18:36:04 +000012261 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012262 // out, perform the transformation. Note, we don't know whether Scale is
12263 // signed or not. We'll use unsigned version of division/modulo
12264 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000012265 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012266 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012267 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012268 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000012269 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000012270 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12271 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012272 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000012273 }
12274
12275 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000012276 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012277 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012278 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012279 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12280 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12281 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012282 // The NewGEP must be pointer typed, so must the old one -> BitCast
12283 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012284 }
12285 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012286 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012287 }
Chris Lattner58407792009-01-09 04:53:57 +000012288
Chris Lattner46cd5a12009-01-09 05:44:56 +000012289 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000012290 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000012291 /// Y = gep X, <...constant indices...>
12292 /// into a gep of the original struct. This is important for SROA and alias
12293 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000012294 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012295 if (TD &&
12296 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012297 // Determine how much the GEP moves the pointer. We are guaranteed to get
12298 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000012299 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000012300 int64_t Offset = OffsetV->getSExtValue();
12301
12302 // If this GEP instruction doesn't move the pointer, just replace the GEP
12303 // with a bitcast of the real input to the dest type.
12304 if (Offset == 0) {
12305 // If the bitcast is of an allocation, and the allocation will be
12306 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000012307 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000012308 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012309 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12310 if (Instruction *I = visitBitCast(*BCI)) {
12311 if (I != BCI) {
12312 I->takeName(BCI);
12313 BCI->getParent()->getInstList().insert(BCI, I);
12314 ReplaceInstUsesWith(*BCI, I);
12315 }
12316 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012317 }
Chris Lattner58407792009-01-09 04:53:57 +000012318 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012319 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012320 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012321
12322 // Otherwise, if the offset is non-zero, we need to find out if there is a
12323 // field at Offset in 'A's type. If so, we can pull the cast through the
12324 // GEP.
12325 SmallVector<Value*, 8> NewIndices;
12326 const Type *InTy =
12327 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000012328 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012329 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12330 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12331 NewIndices.end()) :
12332 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12333 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012334
12335 if (NGEP->getType() == GEP.getType())
12336 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012337 NGEP->takeName(&GEP);
12338 return new BitCastInst(NGEP, GEP.getType());
12339 }
Chris Lattner58407792009-01-09 04:53:57 +000012340 }
12341 }
12342
Chris Lattner8a2a3112001-12-14 16:52:21 +000012343 return 0;
12344}
12345
Victor Hernandez7b929da2009-10-23 21:09:37 +000012346Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012347 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012348 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012349 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12350 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012351 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012352 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012353 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012354 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012355
Chris Lattner0864acf2002-11-04 16:18:53 +000012356 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012357 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012358 //
12359 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012360 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012361
12362 // Now that I is pointing to the first non-allocation-inst in the block,
12363 // insert our getelementptr instruction...
12364 //
Owen Anderson1d0be152009-08-13 21:58:54 +000012365 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012366 Value *Idx[2];
12367 Idx[0] = NullIdx;
12368 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012369 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12370 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012371
12372 // Now make everything use the getelementptr instead of the original
12373 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012374 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012375 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012376 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012377 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012378 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012379
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012380 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012381 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012382 // Note that we only do this for alloca's, because malloc should allocate
12383 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012384 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012385 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012386
12387 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12388 if (AI.getAlignment() == 0)
12389 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12390 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012391
Chris Lattner0864acf2002-11-04 16:18:53 +000012392 return 0;
12393}
12394
Victor Hernandez66284e02009-10-24 04:23:03 +000012395Instruction *InstCombiner::visitFree(Instruction &FI) {
12396 Value *Op = FI.getOperand(1);
12397
12398 // free undef -> unreachable.
12399 if (isa<UndefValue>(Op)) {
12400 // Insert a new store to null because we cannot modify the CFG here.
12401 new StoreInst(ConstantInt::getTrue(*Context),
12402 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12403 return EraseInstFromFunction(FI);
12404 }
12405
12406 // If we have 'free null' delete the instruction. This can happen in stl code
12407 // when lots of inlining happens.
12408 if (isa<ConstantPointerNull>(Op))
12409 return EraseInstFromFunction(FI);
12410
Victor Hernandez046e78c2009-10-26 23:43:48 +000012411 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012412 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012413 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12414 if (Op->hasOneUse() && CI->hasOneUse()) {
12415 EraseInstFromFunction(FI);
12416 EraseInstFromFunction(*CI);
12417 return EraseInstFromFunction(*cast<Instruction>(Op));
12418 }
12419 } else {
12420 // Op is a call to malloc
12421 if (Op->hasOneUse()) {
12422 EraseInstFromFunction(FI);
12423 return EraseInstFromFunction(*cast<Instruction>(Op));
12424 }
12425 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012426 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012427
12428 return 0;
12429}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012430
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012431/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012432static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012433 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012434 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012435 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000012436 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000012437
Mon P Wang6753f952009-02-07 22:19:29 +000012438 const PointerType *DestTy = cast<PointerType>(CI->getType());
12439 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012440 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012441
12442 // If the address spaces don't match, don't eliminate the cast.
12443 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12444 return 0;
12445
Chris Lattnerb89e0712004-07-13 01:49:43 +000012446 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012447
Reid Spencer42230162007-01-22 05:51:25 +000012448 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012449 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012450 // If the source is an array, the code below will not succeed. Check to
12451 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12452 // constants.
12453 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12454 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12455 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012456 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012457 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12458 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012459 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012460 SrcTy = cast<PointerType>(CastOp->getType());
12461 SrcPTy = SrcTy->getElementType();
12462 }
12463
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012464 if (IC.getTargetData() &&
12465 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012466 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012467 // Do not allow turning this into a load of an integer, which is then
12468 // casted to a pointer, this pessimizes pointer analysis a lot.
12469 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012470 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12471 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012472
Chris Lattnerf9527852005-01-31 04:50:46 +000012473 // Okay, we are casting from one integer or pointer type to another of
12474 // the same size. Instead of casting the pointer before the load, cast
12475 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012476 Value *NewLoad =
12477 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012478 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012479 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012480 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012481 }
12482 }
12483 return 0;
12484}
12485
Chris Lattner833b8a42003-06-26 05:06:25 +000012486Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12487 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012488
Dan Gohman9941f742007-07-20 16:34:21 +000012489 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012490 if (TD) {
12491 unsigned KnownAlign =
12492 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12493 if (KnownAlign >
12494 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12495 LI.getAlignment()))
12496 LI.setAlignment(KnownAlign);
12497 }
Dan Gohman9941f742007-07-20 16:34:21 +000012498
Chris Lattner963f4ba2009-08-30 20:36:46 +000012499 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012500 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012501 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012502 return Res;
12503
12504 // None of the following transforms are legal for volatile loads.
12505 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012506
Dan Gohman2276a7b2008-10-15 23:19:35 +000012507 // Do really simple store-to-load forwarding and load CSE, to catch cases
12508 // where there are several consequtive memory accesses to the same location,
12509 // separated by a few arithmetic operations.
12510 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012511 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12512 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012513
Chris Lattner878e4942009-10-22 06:25:11 +000012514 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012515 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12516 const Value *GEPI0 = GEPI->getOperand(0);
12517 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012518 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012519 // Insert a new store to null instruction before the load to indicate
12520 // that this code is not reachable. We do this instead of inserting
12521 // an unreachable instruction directly because we cannot modify the
12522 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012523 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012524 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012525 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012526 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012527 }
Chris Lattner37366c12005-05-01 04:24:53 +000012528
Chris Lattner878e4942009-10-22 06:25:11 +000012529 // load null/undef -> unreachable
12530 // TODO: Consider a target hook for valid address spaces for this xform.
12531 if (isa<UndefValue>(Op) ||
12532 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12533 // Insert a new store to null instruction before the load to indicate that
12534 // this code is not reachable. We do this instead of inserting an
12535 // unreachable instruction directly because we cannot modify the CFG.
12536 new StoreInst(UndefValue::get(LI.getType()),
12537 Constant::getNullValue(Op->getType()), &LI);
12538 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012539 }
Chris Lattner878e4942009-10-22 06:25:11 +000012540
12541 // Instcombine load (constantexpr_cast global) -> cast (load global)
12542 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12543 if (CE->isCast())
12544 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12545 return Res;
12546
Chris Lattner37366c12005-05-01 04:24:53 +000012547 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012548 // Change select and PHI nodes to select values instead of addresses: this
12549 // helps alias analysis out a lot, allows many others simplifications, and
12550 // exposes redundancy in the code.
12551 //
12552 // Note that we cannot do the transformation unless we know that the
12553 // introduced loads cannot trap! Something like this is valid as long as
12554 // the condition is always false: load (select bool %C, int* null, int* %G),
12555 // but it would not be valid if we transformed it to load from null
12556 // unconditionally.
12557 //
12558 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12559 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012560 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12561 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012562 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12563 SI->getOperand(1)->getName()+".val");
12564 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12565 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012566 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012567 }
12568
Chris Lattner684fe212004-09-23 15:46:00 +000012569 // load (select (cond, null, P)) -> load P
12570 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12571 if (C->isNullValue()) {
12572 LI.setOperand(0, SI->getOperand(2));
12573 return &LI;
12574 }
12575
12576 // load (select (cond, P, null)) -> load P
12577 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12578 if (C->isNullValue()) {
12579 LI.setOperand(0, SI->getOperand(1));
12580 return &LI;
12581 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012582 }
12583 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012584 return 0;
12585}
12586
Reid Spencer55af2b52007-01-19 21:20:31 +000012587/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012588/// when possible. This makes it generally easy to do alias analysis and/or
12589/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012590static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12591 User *CI = cast<User>(SI.getOperand(1));
12592 Value *CastOp = CI->getOperand(0);
12593
12594 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012595 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12596 if (SrcTy == 0) return 0;
12597
12598 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012599
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012600 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12601 return 0;
12602
Chris Lattner3914f722009-01-24 01:00:13 +000012603 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12604 /// to its first element. This allows us to handle things like:
12605 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12606 /// on 32-bit hosts.
12607 SmallVector<Value*, 4> NewGEPIndices;
12608
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012609 // If the source is an array, the code below will not succeed. Check to
12610 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12611 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012612 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12613 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012614 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012615 NewGEPIndices.push_back(Zero);
12616
12617 while (1) {
12618 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012619 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012620 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012621 NewGEPIndices.push_back(Zero);
12622 SrcPTy = STy->getElementType(0);
12623 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12624 NewGEPIndices.push_back(Zero);
12625 SrcPTy = ATy->getElementType();
12626 } else {
12627 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012628 }
Chris Lattner3914f722009-01-24 01:00:13 +000012629 }
12630
Owen Andersondebcb012009-07-29 22:17:13 +000012631 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012632 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012633
12634 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12635 return 0;
12636
Chris Lattner71759c42009-01-16 20:12:52 +000012637 // If the pointers point into different address spaces or if they point to
12638 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012639 if (!IC.getTargetData() ||
12640 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012641 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012642 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12643 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012644 return 0;
12645
12646 // Okay, we are casting from one integer or pointer type to another of
12647 // the same size. Instead of casting the pointer before
12648 // the store, cast the value to be stored.
12649 Value *NewCast;
12650 Value *SIOp0 = SI.getOperand(0);
12651 Instruction::CastOps opcode = Instruction::BitCast;
12652 const Type* CastSrcTy = SIOp0->getType();
12653 const Type* CastDstTy = SrcPTy;
12654 if (isa<PointerType>(CastDstTy)) {
12655 if (CastSrcTy->isInteger())
12656 opcode = Instruction::IntToPtr;
12657 } else if (isa<IntegerType>(CastDstTy)) {
12658 if (isa<PointerType>(SIOp0->getType()))
12659 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012660 }
Chris Lattner3914f722009-01-24 01:00:13 +000012661
12662 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12663 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012664 if (!NewGEPIndices.empty())
12665 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12666 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012667
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012668 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12669 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012670 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012671}
12672
Chris Lattner4aebaee2008-11-27 08:56:30 +000012673/// equivalentAddressValues - Test if A and B will obviously have the same
12674/// value. This includes recognizing that %t0 and %t1 will have the same
12675/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012676/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012677/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012678/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012679/// %t2 = load i32* %t1
12680///
12681static bool equivalentAddressValues(Value *A, Value *B) {
12682 // Test if the values are trivially equivalent.
12683 if (A == B) return true;
12684
12685 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012686 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12687 // its only used to compare two uses within the same basic block, which
12688 // means that they'll always either have the same value or one of them
12689 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012690 if (isa<BinaryOperator>(A) ||
12691 isa<CastInst>(A) ||
12692 isa<PHINode>(A) ||
12693 isa<GetElementPtrInst>(A))
12694 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012695 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012696 return true;
12697
12698 // Otherwise they may not be equivalent.
12699 return false;
12700}
12701
Dale Johannesen4945c652009-03-03 21:26:39 +000012702// If this instruction has two uses, one of which is a llvm.dbg.declare,
12703// return the llvm.dbg.declare.
12704DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12705 if (!V->hasNUses(2))
12706 return 0;
12707 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12708 UI != E; ++UI) {
12709 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12710 return DI;
12711 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12712 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12713 return DI;
12714 }
12715 }
12716 return 0;
12717}
12718
Chris Lattner2f503e62005-01-31 05:36:43 +000012719Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12720 Value *Val = SI.getOperand(0);
12721 Value *Ptr = SI.getOperand(1);
12722
Chris Lattner836692d2007-01-15 06:51:56 +000012723 // If the RHS is an alloca with a single use, zapify the store, making the
12724 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012725 // If the RHS is an alloca with a two uses, the other one being a
12726 // llvm.dbg.declare, zapify the store and the declare, making the
12727 // alloca dead. We must do this to prevent declare's from affecting
12728 // codegen.
12729 if (!SI.isVolatile()) {
12730 if (Ptr->hasOneUse()) {
12731 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012732 EraseInstFromFunction(SI);
12733 ++NumCombined;
12734 return 0;
12735 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012736 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12737 if (isa<AllocaInst>(GEP->getOperand(0))) {
12738 if (GEP->getOperand(0)->hasOneUse()) {
12739 EraseInstFromFunction(SI);
12740 ++NumCombined;
12741 return 0;
12742 }
12743 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12744 EraseInstFromFunction(*DI);
12745 EraseInstFromFunction(SI);
12746 ++NumCombined;
12747 return 0;
12748 }
12749 }
12750 }
12751 }
12752 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12753 EraseInstFromFunction(*DI);
12754 EraseInstFromFunction(SI);
12755 ++NumCombined;
12756 return 0;
12757 }
Chris Lattner836692d2007-01-15 06:51:56 +000012758 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012759
Dan Gohman9941f742007-07-20 16:34:21 +000012760 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012761 if (TD) {
12762 unsigned KnownAlign =
12763 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12764 if (KnownAlign >
12765 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12766 SI.getAlignment()))
12767 SI.setAlignment(KnownAlign);
12768 }
Dan Gohman9941f742007-07-20 16:34:21 +000012769
Dale Johannesenacb51a32009-03-03 01:43:03 +000012770 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012771 // stores to the same location, separated by a few arithmetic operations. This
12772 // situation often occurs with bitfield accesses.
12773 BasicBlock::iterator BBI = &SI;
12774 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12775 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012776 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012777 // Don't count debug info directives, lest they affect codegen,
12778 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12779 // It is necessary for correctness to skip those that feed into a
12780 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012781 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012782 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012783 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012784 continue;
12785 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012786
12787 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12788 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012789 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12790 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012791 ++NumDeadStore;
12792 ++BBI;
12793 EraseInstFromFunction(*PrevSI);
12794 continue;
12795 }
12796 break;
12797 }
12798
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012799 // If this is a load, we have to stop. However, if the loaded value is from
12800 // the pointer we're loading and is producing the pointer we're storing,
12801 // then *this* store is dead (X = load P; store X -> P).
12802 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012803 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12804 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012805 EraseInstFromFunction(SI);
12806 ++NumCombined;
12807 return 0;
12808 }
12809 // Otherwise, this is a load from some other location. Stores before it
12810 // may not be dead.
12811 break;
12812 }
12813
Chris Lattner9ca96412006-02-08 03:25:32 +000012814 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012815 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012816 break;
12817 }
12818
12819
12820 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012821
12822 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012823 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012824 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012825 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012826 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012827 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012828 ++NumCombined;
12829 }
12830 return 0; // Do not modify these!
12831 }
12832
12833 // store undef, Ptr -> noop
12834 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012835 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012836 ++NumCombined;
12837 return 0;
12838 }
12839
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012840 // If the pointer destination is a cast, see if we can fold the cast into the
12841 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012842 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012843 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12844 return Res;
12845 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012846 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012847 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12848 return Res;
12849
Chris Lattner408902b2005-09-12 23:23:25 +000012850
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012851 // If this store is the last instruction in the basic block (possibly
12852 // excepting debug info instructions and the pointer bitcasts that feed
12853 // into them), and if the block ends with an unconditional branch, try
12854 // to move it to the successor block.
12855 BBI = &SI;
12856 do {
12857 ++BBI;
12858 } while (isa<DbgInfoIntrinsic>(BBI) ||
12859 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012860 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012861 if (BI->isUnconditional())
12862 if (SimplifyStoreAtEndOfBlock(SI))
12863 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012864
Chris Lattner2f503e62005-01-31 05:36:43 +000012865 return 0;
12866}
12867
Chris Lattner3284d1f2007-04-15 00:07:55 +000012868/// SimplifyStoreAtEndOfBlock - Turn things like:
12869/// if () { *P = v1; } else { *P = v2 }
12870/// into a phi node with a store in the successor.
12871///
Chris Lattner31755a02007-04-15 01:02:18 +000012872/// Simplify things like:
12873/// *P = v1; if () { *P = v2; }
12874/// into a phi node with a store in the successor.
12875///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012876bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12877 BasicBlock *StoreBB = SI.getParent();
12878
12879 // Check to see if the successor block has exactly two incoming edges. If
12880 // so, see if the other predecessor contains a store to the same location.
12881 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012882 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012883
12884 // Determine whether Dest has exactly two predecessors and, if so, compute
12885 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012886 pred_iterator PI = pred_begin(DestBB);
12887 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012888 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012889 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012890 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012891 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012892 return false;
12893
12894 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012895 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012896 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012897 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012898 }
Chris Lattner31755a02007-04-15 01:02:18 +000012899 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012900 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012901
12902 // Bail out if all the relevant blocks aren't distinct (this can happen,
12903 // for example, if SI is in an infinite loop)
12904 if (StoreBB == DestBB || OtherBB == DestBB)
12905 return false;
12906
Chris Lattner31755a02007-04-15 01:02:18 +000012907 // Verify that the other block ends in a branch and is not otherwise empty.
12908 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012909 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012910 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012911 return false;
12912
Chris Lattner31755a02007-04-15 01:02:18 +000012913 // If the other block ends in an unconditional branch, check for the 'if then
12914 // else' case. there is an instruction before the branch.
12915 StoreInst *OtherStore = 0;
12916 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012917 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012918 // Skip over debugging info.
12919 while (isa<DbgInfoIntrinsic>(BBI) ||
12920 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12921 if (BBI==OtherBB->begin())
12922 return false;
12923 --BBI;
12924 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012925 // If this isn't a store, isn't a store to the same location, or if the
12926 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012927 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012928 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12929 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012930 return false;
12931 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012932 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012933 // destinations is StoreBB, then we have the if/then case.
12934 if (OtherBr->getSuccessor(0) != StoreBB &&
12935 OtherBr->getSuccessor(1) != StoreBB)
12936 return false;
12937
12938 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012939 // if/then triangle. See if there is a store to the same ptr as SI that
12940 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012941 for (;; --BBI) {
12942 // Check to see if we find the matching store.
12943 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012944 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12945 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012946 return false;
12947 break;
12948 }
Eli Friedman6903a242008-06-13 22:02:12 +000012949 // If we find something that may be using or overwriting the stored
12950 // value, or if we run out of instructions, we can't do the xform.
12951 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012952 BBI == OtherBB->begin())
12953 return false;
12954 }
12955
12956 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012957 // make sure nothing reads or overwrites the stored value in
12958 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012959 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12960 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012961 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012962 return false;
12963 }
12964 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012965
Chris Lattner31755a02007-04-15 01:02:18 +000012966 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012967 Value *MergedVal = OtherStore->getOperand(0);
12968 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012969 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012970 PN->reserveOperandSpace(2);
12971 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012972 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12973 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012974 }
12975
12976 // Advance to a place where it is safe to insert the new store and
12977 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012978 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012979 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012980 OtherStore->isVolatile(),
12981 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012982
12983 // Nuke the old stores.
12984 EraseInstFromFunction(SI);
12985 EraseInstFromFunction(*OtherStore);
12986 ++NumCombined;
12987 return true;
12988}
12989
Chris Lattner2f503e62005-01-31 05:36:43 +000012990
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012991Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12992 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012993 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012994 BasicBlock *TrueDest;
12995 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012996 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012997 !isa<Constant>(X)) {
12998 // Swap Destinations and condition...
12999 BI.setCondition(X);
13000 BI.setSuccessor(0, FalseDest);
13001 BI.setSuccessor(1, TrueDest);
13002 return &BI;
13003 }
13004
Reid Spencere4d87aa2006-12-23 06:05:41 +000013005 // Cannonicalize fcmp_one -> fcmp_oeq
13006 FCmpInst::Predicate FPred; Value *Y;
13007 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000013008 TrueDest, FalseDest)) &&
13009 BI.getCondition()->hasOneUse())
13010 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
13011 FPred == FCmpInst::FCMP_OGE) {
13012 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
13013 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
13014
13015 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000013016 BI.setSuccessor(0, FalseDest);
13017 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000013018 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000013019 return &BI;
13020 }
13021
13022 // Cannonicalize icmp_ne -> icmp_eq
13023 ICmpInst::Predicate IPred;
13024 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000013025 TrueDest, FalseDest)) &&
13026 BI.getCondition()->hasOneUse())
13027 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
13028 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
13029 IPred == ICmpInst::ICMP_SGE) {
13030 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
13031 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
13032 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000013033 BI.setSuccessor(0, FalseDest);
13034 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000013035 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000013036 return &BI;
13037 }
Misha Brukmanfd939082005-04-21 23:48:37 +000013038
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000013039 return 0;
13040}
Chris Lattner0864acf2002-11-04 16:18:53 +000013041
Chris Lattner46238a62004-07-03 00:26:11 +000013042Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
13043 Value *Cond = SI.getCondition();
13044 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
13045 if (I->getOpcode() == Instruction::Add)
13046 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
13047 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
13048 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013049 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000013050 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000013051 AddRHS));
13052 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000013053 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000013054 return &SI;
13055 }
13056 }
13057 return 0;
13058}
13059
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013060Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013061 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013062
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013063 if (!EV.hasIndices())
13064 return ReplaceInstUsesWith(EV, Agg);
13065
13066 if (Constant *C = dyn_cast<Constant>(Agg)) {
13067 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013068 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013069
13070 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000013071 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013072
13073 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
13074 // Extract the element indexed by the first index out of the constant
13075 Value *V = C->getOperand(*EV.idx_begin());
13076 if (EV.getNumIndices() > 1)
13077 // Extract the remaining indices out of the constant indexed by the
13078 // first index
13079 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
13080 else
13081 return ReplaceInstUsesWith(EV, V);
13082 }
13083 return 0; // Can't handle other constants
13084 }
13085 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
13086 // We're extracting from an insertvalue instruction, compare the indices
13087 const unsigned *exti, *exte, *insi, *inse;
13088 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
13089 exte = EV.idx_end(), inse = IV->idx_end();
13090 exti != exte && insi != inse;
13091 ++exti, ++insi) {
13092 if (*insi != *exti)
13093 // The insert and extract both reference distinctly different elements.
13094 // This means the extract is not influenced by the insert, and we can
13095 // replace the aggregate operand of the extract with the aggregate
13096 // operand of the insert. i.e., replace
13097 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13098 // %E = extractvalue { i32, { i32 } } %I, 0
13099 // with
13100 // %E = extractvalue { i32, { i32 } } %A, 0
13101 return ExtractValueInst::Create(IV->getAggregateOperand(),
13102 EV.idx_begin(), EV.idx_end());
13103 }
13104 if (exti == exte && insi == inse)
13105 // Both iterators are at the end: Index lists are identical. Replace
13106 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13107 // %C = extractvalue { i32, { i32 } } %B, 1, 0
13108 // with "i32 42"
13109 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13110 if (exti == exte) {
13111 // The extract list is a prefix of the insert list. i.e. replace
13112 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13113 // %E = extractvalue { i32, { i32 } } %I, 1
13114 // with
13115 // %X = extractvalue { i32, { i32 } } %A, 1
13116 // %E = insertvalue { i32 } %X, i32 42, 0
13117 // by switching the order of the insert and extract (though the
13118 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000013119 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13120 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013121 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13122 insi, inse);
13123 }
13124 if (insi == inse)
13125 // The insert list is a prefix of the extract list
13126 // We can simply remove the common indices from the extract and make it
13127 // operate on the inserted value instead of the insertvalue result.
13128 // i.e., replace
13129 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13130 // %E = extractvalue { i32, { i32 } } %I, 1, 0
13131 // with
13132 // %E extractvalue { i32 } { i32 42 }, 0
13133 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
13134 exti, exte);
13135 }
Chris Lattner7e606e22009-11-09 07:07:56 +000013136 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13137 // We're extracting from an intrinsic, see if we're the only user, which
13138 // allows us to simplify multiple result intrinsics to simpler things that
13139 // just get one value..
13140 if (II->hasOneUse()) {
13141 // Check if we're grabbing the overflow bit or the result of a 'with
13142 // overflow' intrinsic. If it's the latter we can remove the intrinsic
13143 // and replace it with a traditional binary instruction.
13144 switch (II->getIntrinsicID()) {
13145 case Intrinsic::uadd_with_overflow:
13146 case Intrinsic::sadd_with_overflow:
13147 if (*EV.idx_begin() == 0) { // Normal result.
13148 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13149 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13150 EraseInstFromFunction(*II);
13151 return BinaryOperator::CreateAdd(LHS, RHS);
13152 }
13153 break;
13154 case Intrinsic::usub_with_overflow:
13155 case Intrinsic::ssub_with_overflow:
13156 if (*EV.idx_begin() == 0) { // Normal result.
13157 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13158 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13159 EraseInstFromFunction(*II);
13160 return BinaryOperator::CreateSub(LHS, RHS);
13161 }
13162 break;
13163 case Intrinsic::umul_with_overflow:
13164 case Intrinsic::smul_with_overflow:
13165 if (*EV.idx_begin() == 0) { // Normal result.
13166 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13167 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13168 EraseInstFromFunction(*II);
13169 return BinaryOperator::CreateMul(LHS, RHS);
13170 }
13171 break;
13172 default:
13173 break;
13174 }
13175 }
13176 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013177 // Can't simplify extracts from other values. Note that nested extracts are
13178 // already simplified implicitely by the above (extract ( extract (insert) )
13179 // will be translated into extract ( insert ( extract ) ) first and then just
13180 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013181 return 0;
13182}
13183
Chris Lattner220b0cf2006-03-05 00:22:33 +000013184/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13185/// is to leave as a vector operation.
13186static bool CheapToScalarize(Value *V, bool isConstant) {
13187 if (isa<ConstantAggregateZero>(V))
13188 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013189 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000013190 if (isConstant) return true;
13191 // If all elts are the same, we can extract.
13192 Constant *Op0 = C->getOperand(0);
13193 for (unsigned i = 1; i < C->getNumOperands(); ++i)
13194 if (C->getOperand(i) != Op0)
13195 return false;
13196 return true;
13197 }
13198 Instruction *I = dyn_cast<Instruction>(V);
13199 if (!I) return false;
13200
13201 // Insert element gets simplified to the inserted element or is deleted if
13202 // this is constant idx extract element and its a constant idx insertelt.
13203 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13204 isa<ConstantInt>(I->getOperand(2)))
13205 return true;
13206 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13207 return true;
13208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13209 if (BO->hasOneUse() &&
13210 (CheapToScalarize(BO->getOperand(0), isConstant) ||
13211 CheapToScalarize(BO->getOperand(1), isConstant)))
13212 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000013213 if (CmpInst *CI = dyn_cast<CmpInst>(I))
13214 if (CI->hasOneUse() &&
13215 (CheapToScalarize(CI->getOperand(0), isConstant) ||
13216 CheapToScalarize(CI->getOperand(1), isConstant)))
13217 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000013218
13219 return false;
13220}
13221
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000013222/// Read and decode a shufflevector mask.
13223///
13224/// It turns undef elements into values that are larger than the number of
13225/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000013226static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13227 unsigned NElts = SVI->getType()->getNumElements();
13228 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13229 return std::vector<unsigned>(NElts, 0);
13230 if (isa<UndefValue>(SVI->getOperand(2)))
13231 return std::vector<unsigned>(NElts, 2*NElts);
13232
13233 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013234 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000013235 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13236 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000013237 Result.push_back(NElts*2); // undef -> 8
13238 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000013239 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000013240 return Result;
13241}
13242
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013243/// FindScalarElement - Given a vector and an element number, see if the scalar
13244/// value is already around as a register, for example if it were inserted then
13245/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000013246static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013247 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013248 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13249 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000013250 unsigned Width = PTy->getNumElements();
13251 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013252 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013253
13254 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013255 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013256 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000013257 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000013258 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013259 return CP->getOperand(EltNo);
13260 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13261 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000013262 if (!isa<ConstantInt>(III->getOperand(2)))
13263 return 0;
13264 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013265
13266 // If this is an insert to the element we are looking for, return the
13267 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000013268 if (EltNo == IIElt)
13269 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013270
13271 // Otherwise, the insertelement doesn't modify the value, recurse on its
13272 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000013273 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000013274 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000013275 unsigned LHSWidth =
13276 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000013277 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000013278 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013279 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013280 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013281 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000013282 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013283 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013284 }
13285
13286 // Otherwise, we don't know.
13287 return 0;
13288}
13289
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013290Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000013291 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000013292 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013293 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013294
Dan Gohman07a96762007-07-16 14:29:03 +000013295 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000013296 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000013297 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013298
Reid Spencer9d6565a2007-02-15 02:26:10 +000013299 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000013300 // If vector val is constant with all elements the same, replace EI with
13301 // that element. When the elements are not identical, we cannot replace yet
13302 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000013303 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013304 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000013305 if (C->getOperand(i) != op0) {
13306 op0 = 0;
13307 break;
13308 }
13309 if (op0)
13310 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013311 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000013312
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013313 // If extracting a specified index from the vector, see if we can recursively
13314 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000013315 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000013316 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013317 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013318
13319 // If this is extracting an invalid index, turn this into undef, to avoid
13320 // crashing the code below.
13321 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013322 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013323
Chris Lattner867b99f2006-10-05 06:55:50 +000013324 // This instruction only demands the single element from the input vector.
13325 // If the input vector has a single use, simplify it based on this use
13326 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013327 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013328 APInt UndefElts(VectorWidth, 0);
13329 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013330 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013331 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013332 EI.setOperand(0, V);
13333 return &EI;
13334 }
13335 }
13336
Owen Andersond672ecb2009-07-03 00:17:18 +000013337 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013338 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013339
13340 // If the this extractelement is directly using a bitcast from a vector of
13341 // the same number of elements, see if we can find the source element from
13342 // it. In this case, we will end up needing to bitcast the scalars.
13343 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13344 if (const VectorType *VT =
13345 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13346 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013347 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13348 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013349 return new BitCastInst(Elt, EI.getType());
13350 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013351 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013352
Chris Lattner73fa49d2006-05-25 22:53:38 +000013353 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013354 // Push extractelement into predecessor operation if legal and
13355 // profitable to do so
13356 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13357 if (I->hasOneUse() &&
13358 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13359 Value *newEI0 =
13360 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13361 EI.getName()+".lhs");
13362 Value *newEI1 =
13363 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13364 EI.getName()+".rhs");
13365 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013366 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013367 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013368 // Extracting the inserted element?
13369 if (IE->getOperand(2) == EI.getOperand(1))
13370 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13371 // If the inserted and extracted elements are constants, they must not
13372 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013373 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013374 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013375 EI.setOperand(0, IE->getOperand(0));
13376 return &EI;
13377 }
13378 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13379 // If this is extracting an element from a shufflevector, figure out where
13380 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013381 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13382 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013383 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013384 unsigned LHSWidth =
13385 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13386
13387 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013388 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013389 else if (SrcIdx < LHSWidth*2) {
13390 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013391 Src = SVI->getOperand(1);
13392 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013393 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013394 }
Eric Christophera3500da2009-07-25 02:28:41 +000013395 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000013396 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13397 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013398 }
13399 }
Eli Friedman2451a642009-07-18 23:06:53 +000013400 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013401 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013402 return 0;
13403}
13404
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013405/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13406/// elements from either LHS or RHS, return the shuffle mask and true.
13407/// Otherwise, return false.
13408static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000013409 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013410 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013411 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13412 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013413 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013414
13415 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013416 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013417 return true;
13418 } else if (V == LHS) {
13419 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013420 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013421 return true;
13422 } else if (V == RHS) {
13423 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013424 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013425 return true;
13426 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13427 // If this is an insert of an extract from some other vector, include it.
13428 Value *VecOp = IEI->getOperand(0);
13429 Value *ScalarOp = IEI->getOperand(1);
13430 Value *IdxOp = IEI->getOperand(2);
13431
Chris Lattnerd929f062006-04-27 21:14:21 +000013432 if (!isa<ConstantInt>(IdxOp))
13433 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013434 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013435
13436 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13437 // Okay, we can handle this if the vector we are insertinting into is
13438 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013439 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013440 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013441 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013442 return true;
13443 }
13444 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13445 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013446 EI->getOperand(0)->getType() == V->getType()) {
13447 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013448 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013449
13450 // This must be extracting from either LHS or RHS.
13451 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13452 // Okay, we can handle this if the vector we are insertinting into is
13453 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013454 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013455 // If so, update the mask to reflect the inserted value.
13456 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013457 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013458 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013459 } else {
13460 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013461 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013462 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013463
13464 }
13465 return true;
13466 }
13467 }
13468 }
13469 }
13470 }
13471 // TODO: Handle shufflevector here!
13472
13473 return false;
13474}
13475
13476/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13477/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13478/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013479static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013480 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013481 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013482 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013483 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013484 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013485
13486 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013487 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013488 return V;
13489 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013490 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013491 return V;
13492 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13493 // If this is an insert of an extract from some other vector, include it.
13494 Value *VecOp = IEI->getOperand(0);
13495 Value *ScalarOp = IEI->getOperand(1);
13496 Value *IdxOp = IEI->getOperand(2);
13497
13498 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13499 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13500 EI->getOperand(0)->getType() == V->getType()) {
13501 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013502 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13503 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013504
13505 // Either the extracted from or inserted into vector must be RHSVec,
13506 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013507 if (EI->getOperand(0) == RHS || RHS == 0) {
13508 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013509 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013510 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013511 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013512 return V;
13513 }
13514
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013515 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013516 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13517 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013518 // Everything but the extracted element is replaced with the RHS.
13519 for (unsigned i = 0; i != NumElts; ++i) {
13520 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013521 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013522 }
13523 return V;
13524 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013525
13526 // If this insertelement is a chain that comes from exactly these two
13527 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013528 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13529 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013530 return EI->getOperand(0);
13531
Chris Lattnerefb47352006-04-15 01:39:45 +000013532 }
13533 }
13534 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013535 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013536
13537 // Otherwise, can't do anything fancy. Return an identity vector.
13538 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013539 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013540 return V;
13541}
13542
13543Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13544 Value *VecOp = IE.getOperand(0);
13545 Value *ScalarOp = IE.getOperand(1);
13546 Value *IdxOp = IE.getOperand(2);
13547
Chris Lattner599ded12007-04-09 01:11:16 +000013548 // Inserting an undef or into an undefined place, remove this.
13549 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13550 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013551
Chris Lattnerefb47352006-04-15 01:39:45 +000013552 // If the inserted element was extracted from some other vector, and if the
13553 // indexes are constant, try to turn this into a shufflevector operation.
13554 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13555 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13556 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013557 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013558 unsigned ExtractedIdx =
13559 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013560 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013561
13562 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13563 return ReplaceInstUsesWith(IE, VecOp);
13564
13565 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013566 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013567
13568 // If we are extracting a value from a vector, then inserting it right
13569 // back into the same place, just use the input vector.
13570 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13571 return ReplaceInstUsesWith(IE, VecOp);
13572
Chris Lattnerefb47352006-04-15 01:39:45 +000013573 // If this insertelement isn't used by some other insertelement, turn it
13574 // (and any insertelements it points to), into one big shuffle.
13575 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13576 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013577 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013578 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013579 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013580 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013581 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013582 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013583 }
13584 }
13585 }
13586
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013587 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13588 APInt UndefElts(VWidth, 0);
13589 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13590 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13591 return &IE;
13592
Chris Lattnerefb47352006-04-15 01:39:45 +000013593 return 0;
13594}
13595
13596
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013597Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13598 Value *LHS = SVI.getOperand(0);
13599 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013600 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013601
13602 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013603
Chris Lattner867b99f2006-10-05 06:55:50 +000013604 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013605 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013606 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013607
Dan Gohman488fbfc2008-09-09 18:11:14 +000013608 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013609
13610 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13611 return 0;
13612
Evan Cheng388df622009-02-03 10:05:09 +000013613 APInt UndefElts(VWidth, 0);
13614 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13615 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013616 LHS = SVI.getOperand(0);
13617 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013618 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013619 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013620
Chris Lattner863bcff2006-05-25 23:48:38 +000013621 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13622 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13623 if (LHS == RHS || isa<UndefValue>(LHS)) {
13624 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013625 // shuffle(undef,undef,mask) -> undef.
13626 return ReplaceInstUsesWith(SVI, LHS);
13627 }
13628
Chris Lattner863bcff2006-05-25 23:48:38 +000013629 // Remap any references to RHS to use LHS.
13630 std::vector<Constant*> Elts;
13631 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013632 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013633 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013634 else {
13635 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013636 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013637 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013638 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013639 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013640 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013641 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013642 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013643 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013644 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013645 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013646 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013647 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013648 LHS = SVI.getOperand(0);
13649 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013650 MadeChange = true;
13651 }
13652
Chris Lattner7b2e27922006-05-26 00:29:06 +000013653 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013654 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013655
Chris Lattner863bcff2006-05-25 23:48:38 +000013656 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13657 if (Mask[i] >= e*2) continue; // Ignore undef values.
13658 // Is this an identity shuffle of the LHS value?
13659 isLHSID &= (Mask[i] == i);
13660
13661 // Is this an identity shuffle of the RHS value?
13662 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013663 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013664
Chris Lattner863bcff2006-05-25 23:48:38 +000013665 // Eliminate identity shuffles.
13666 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13667 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013668
Chris Lattner7b2e27922006-05-26 00:29:06 +000013669 // If the LHS is a shufflevector itself, see if we can combine it with this
13670 // one without producing an unusual shuffle. Here we are really conservative:
13671 // we are absolutely afraid of producing a shuffle mask not in the input
13672 // program, because the code gen may not be smart enough to turn a merged
13673 // shuffle into two specific shuffles: it may produce worse code. As such,
13674 // we only merge two shuffles if the result is one of the two input shuffle
13675 // masks. In this case, merging the shuffles just removes one instruction,
13676 // which we know is safe. This is good for things like turning:
13677 // (splat(splat)) -> splat.
13678 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13679 if (isa<UndefValue>(RHS)) {
13680 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13681
David Greenef941d292009-11-16 21:52:23 +000013682 if (LHSMask.size() == Mask.size()) {
13683 std::vector<unsigned> NewMask;
13684 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013685 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013686 NewMask.push_back(2*e);
13687 else
13688 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013689
David Greenef941d292009-11-16 21:52:23 +000013690 // If the result mask is equal to the src shuffle or this
13691 // shuffle mask, do the replacement.
13692 if (NewMask == LHSMask || NewMask == Mask) {
13693 unsigned LHSInNElts =
13694 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13695 getNumElements();
13696 std::vector<Constant*> Elts;
13697 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13698 if (NewMask[i] >= LHSInNElts*2) {
13699 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13700 } else {
13701 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13702 NewMask[i]));
13703 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013704 }
David Greenef941d292009-11-16 21:52:23 +000013705 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13706 LHSSVI->getOperand(1),
13707 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013708 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013709 }
13710 }
13711 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013712
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013713 return MadeChange ? &SVI : 0;
13714}
13715
13716
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013717
Chris Lattnerea1c4542004-12-08 23:43:58 +000013718
13719/// TryToSinkInstruction - Try to move the specified instruction from its
13720/// current block into the beginning of DestBlock, which can only happen if it's
13721/// safe to move the instruction past all of the instructions between it and the
13722/// end of its block.
13723static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13724 assert(I->hasOneUse() && "Invariants didn't hold!");
13725
Chris Lattner108e9022005-10-27 17:13:11 +000013726 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013727 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013728 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013729
Chris Lattnerea1c4542004-12-08 23:43:58 +000013730 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013731 if (isa<AllocaInst>(I) && I->getParent() ==
13732 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013733 return false;
13734
Chris Lattner96a52a62004-12-09 07:14:34 +000013735 // We can only sink load instructions if there is nothing between the load and
13736 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013737 if (I->mayReadFromMemory()) {
13738 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013739 Scan != E; ++Scan)
13740 if (Scan->mayWriteToMemory())
13741 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013742 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013743
Dan Gohman02dea8b2008-05-23 21:05:58 +000013744 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013745
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013746 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013747 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013748 ++NumSunkInst;
13749 return true;
13750}
13751
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013752
13753/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13754/// all reachable code to the worklist.
13755///
13756/// This has a couple of tricks to make the code faster and more powerful. In
13757/// particular, we constant fold and DCE instructions as we go, to avoid adding
13758/// them to the worklist (this significantly speeds up instcombine on code where
13759/// many instructions are dead or constant). Additionally, if we find a branch
13760/// whose condition is a known constant, we only visit the reachable successors.
13761///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013762static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013763 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013764 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013765 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013766 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013767 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013768 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013769
13770 std::vector<Instruction*> InstrsForInstCombineWorklist;
13771 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013772
Chris Lattner2ee743b2009-10-15 04:59:28 +000013773 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13774
Chris Lattner2c7718a2007-03-23 19:17:18 +000013775 while (!Worklist.empty()) {
13776 BB = Worklist.back();
13777 Worklist.pop_back();
13778
13779 // We have now visited this block! If we've already been here, ignore it.
13780 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013781
Chris Lattner2c7718a2007-03-23 19:17:18 +000013782 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13783 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013784
Chris Lattner2c7718a2007-03-23 19:17:18 +000013785 // DCE instruction if trivially dead.
13786 if (isInstructionTriviallyDead(Inst)) {
13787 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013788 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013789 Inst->eraseFromParent();
13790 continue;
13791 }
13792
13793 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013794 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013795 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013796 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13797 << *Inst << '\n');
13798 Inst->replaceAllUsesWith(C);
13799 ++NumConstProp;
13800 Inst->eraseFromParent();
13801 continue;
13802 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013803
13804
13805
13806 if (TD) {
13807 // See if we can constant fold its operands.
13808 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13809 i != e; ++i) {
13810 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13811 if (CE == 0) continue;
13812
13813 // If we already folded this constant, don't try again.
13814 if (!FoldedConstants.insert(CE))
13815 continue;
13816
Chris Lattner7b550cc2009-11-06 04:27:31 +000013817 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013818 if (NewC && NewC != CE) {
13819 *i = NewC;
13820 MadeIRChange = true;
13821 }
13822 }
13823 }
13824
Devang Patel7fe1dec2008-11-19 18:56:50 +000013825
Chris Lattner67f7d542009-10-12 03:58:40 +000013826 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013827 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013828
13829 // Recursively visit successors. If this is a branch or switch on a
13830 // constant, only visit the reachable successor.
13831 TerminatorInst *TI = BB->getTerminator();
13832 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13833 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13834 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013835 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013836 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013837 continue;
13838 }
13839 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13840 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13841 // See if this is an explicit destination.
13842 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13843 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013844 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013845 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013846 continue;
13847 }
13848
13849 // Otherwise it is the default destination.
13850 Worklist.push_back(SI->getSuccessor(0));
13851 continue;
13852 }
13853 }
13854
13855 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13856 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013857 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013858
13859 // Once we've found all of the instructions to add to instcombine's worklist,
13860 // add them in reverse order. This way instcombine will visit from the top
13861 // of the function down. This jives well with the way that it adds all uses
13862 // of instructions to the worklist after doing a transformation, thus avoiding
13863 // some N^2 behavior in pathological cases.
13864 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13865 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013866
13867 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013868}
13869
Chris Lattnerec9c3582007-03-03 02:04:50 +000013870bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013871 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013872
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013873 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13874 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013875
Chris Lattnerb3d59702005-07-07 20:40:38 +000013876 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013877 // Do a depth-first traversal of the function, populate the worklist with
13878 // the reachable instructions. Ignore blocks that are not reachable. Keep
13879 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013880 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013881 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013882
Chris Lattnerb3d59702005-07-07 20:40:38 +000013883 // Do a quick scan over the function. If we find any blocks that are
13884 // unreachable, remove any instructions inside of them. This prevents
13885 // the instcombine code from having to deal with some bad special cases.
13886 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13887 if (!Visited.count(BB)) {
13888 Instruction *Term = BB->getTerminator();
13889 while (Term != BB->begin()) { // Remove instrs bottom-up
13890 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013891
Chris Lattnerbdff5482009-08-23 04:37:46 +000013892 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013893 // A debug intrinsic shouldn't force another iteration if we weren't
13894 // going to do one without it.
13895 if (!isa<DbgInfoIntrinsic>(I)) {
13896 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013897 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013898 }
Devang Patel228ebd02009-10-13 22:56:32 +000013899
Devang Patel228ebd02009-10-13 22:56:32 +000013900 // If I is not void type then replaceAllUsesWith undef.
13901 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013902 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013903 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013904 I->eraseFromParent();
13905 }
13906 }
13907 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013908
Chris Lattner873ff012009-08-30 05:55:36 +000013909 while (!Worklist.isEmpty()) {
13910 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013911 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013912
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013913 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013914 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013915 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013916 EraseInstFromFunction(*I);
13917 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013918 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013919 continue;
13920 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013921
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013922 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013923 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013924 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013925 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013926
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013927 // Add operands to the worklist.
13928 ReplaceInstUsesWith(*I, C);
13929 ++NumConstProp;
13930 EraseInstFromFunction(*I);
13931 MadeIRChange = true;
13932 continue;
13933 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013934
Chris Lattnerea1c4542004-12-08 23:43:58 +000013935 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013936 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013937 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013938 Instruction *UserInst = cast<Instruction>(I->use_back());
13939 BasicBlock *UserParent;
13940
13941 // Get the block the use occurs in.
13942 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13943 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13944 else
13945 UserParent = UserInst->getParent();
13946
Chris Lattnerea1c4542004-12-08 23:43:58 +000013947 if (UserParent != BB) {
13948 bool UserIsSuccessor = false;
13949 // See if the user is one of our successors.
13950 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13951 if (*SI == UserParent) {
13952 UserIsSuccessor = true;
13953 break;
13954 }
13955
13956 // If the user is one of our immediate successors, and if that successor
13957 // only has us as a predecessors (we'd have to split the critical edge
13958 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013959 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013960 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013961 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013962 }
13963 }
13964
Chris Lattner74381062009-08-30 07:44:24 +000013965 // Now that we have an instruction, try combining it to simplify it.
13966 Builder->SetInsertPoint(I->getParent(), I);
13967
Reid Spencera9b81012007-03-26 17:44:01 +000013968#ifndef NDEBUG
13969 std::string OrigI;
13970#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013971 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013972 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13973
Chris Lattner90ac28c2002-08-02 19:29:35 +000013974 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013975 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013976 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013977 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013978 DEBUG(errs() << "IC: Old = " << *I << '\n'
13979 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013980
Chris Lattnerf523d062004-06-09 05:08:07 +000013981 // Everything uses the new instruction now.
13982 I->replaceAllUsesWith(Result);
13983
13984 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013985 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013986 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013987
Chris Lattner6934a042007-02-11 01:23:03 +000013988 // Move the name to the new instruction first.
13989 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013990
13991 // Insert the new instruction into the basic block...
13992 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013993 BasicBlock::iterator InsertPos = I;
13994
13995 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13996 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13997 ++InsertPos;
13998
13999 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000014000
Chris Lattner7a1e9242009-08-30 06:13:40 +000014001 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000014002 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000014003#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000014004 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
14005 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000014006#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000014007
Chris Lattner90ac28c2002-08-02 19:29:35 +000014008 // If the instruction was modified, it's possible that it is now dead.
14009 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000014010 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000014011 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000014012 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000014013 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000014014 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000014015 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000014016 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000014017 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000014018 }
14019 }
14020
Chris Lattner873ff012009-08-30 05:55:36 +000014021 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000014022 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014023}
14024
Chris Lattnerec9c3582007-03-03 02:04:50 +000014025
14026bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000014027 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000014028 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000014029 TD = getAnalysisIfAvailable<TargetData>();
14030
Chris Lattner74381062009-08-30 07:44:24 +000014031
14032 /// Builder - This is an IRBuilder that automatically inserts new
14033 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000014034 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000014035 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000014036 InstCombineIRInserter(Worklist));
14037 Builder = &TheBuilder;
14038
Chris Lattnerec9c3582007-03-03 02:04:50 +000014039 bool EverMadeChange = false;
14040
14041 // Iterate while there is work to do.
14042 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000014043 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000014044 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000014045
14046 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000014047 return EverMadeChange;
14048}
14049
Brian Gaeke96d4bf72004-07-27 17:43:21 +000014050FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000014051 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014052}