blob: aec9027db0218359ec4bd1a9907126f354d9209e [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Victor Hernandez83d63912009-09-18 22:35:49 +000045#include "llvm/Analysis/MallocHelper.h"
Chris Lattner173234a2008-06-02 01:18:21 +000046#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000047#include "llvm/Target/TargetData.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000050#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000051#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000052#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000053#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000054#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000055#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000056#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000057#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000058#include "llvm/Support/PatternMatch.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000059#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000060#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000061#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000062#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000063#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000064#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000065#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000066#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000067using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000068using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000069
Chris Lattner0e5f4992006-12-19 21:40:18 +000070STATISTIC(NumCombined , "Number of insts combined");
71STATISTIC(NumConstProp, "Number of constant folds");
72STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000075
Chris Lattner0e5f4992006-12-19 21:40:18 +000076namespace {
Chris Lattner873ff012009-08-30 05:55:36 +000077 /// InstCombineWorklist - This is the worklist management logic for
78 /// InstCombine.
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
82
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
85 public:
86 InstCombineWorklist() {}
87
88 bool isEmpty() const { return Worklist.empty(); }
89
90 /// Add - Add the specified instruction to the worklist if it isn't already
91 /// in it.
92 void Add(Instruction *I) {
Victor Hernandez83d63912009-09-18 22:35:49 +000093 DEBUG(errs() << "IC: ADD: " << *I << '\n');
Chris Lattner873ff012009-08-30 05:55:36 +000094 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95 Worklist.push_back(I);
96 }
97
Chris Lattner3c4e38e2009-08-30 06:27:41 +000098 void AddValue(Value *V) {
99 if (Instruction *I = dyn_cast<Instruction>(V))
100 Add(I);
101 }
102
Chris Lattner7a1e9242009-08-30 06:13:40 +0000103 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000104 void Remove(Instruction *I) {
105 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
106 if (It == WorklistMap.end()) return; // Not in worklist.
107
108 // Don't bother moving everything down, just null out the slot.
109 Worklist[It->second] = 0;
110
111 WorklistMap.erase(It);
112 }
113
114 Instruction *RemoveOne() {
115 Instruction *I = Worklist.back();
116 Worklist.pop_back();
117 WorklistMap.erase(I);
118 return I;
119 }
120
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000121 /// AddUsersToWorkList - When an instruction is simplified, add all users of
122 /// the instruction to the work lists because they might get more simplified
123 /// now.
124 ///
125 void AddUsersToWorkList(Instruction &I) {
126 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127 UI != UE; ++UI)
128 Add(cast<Instruction>(*UI));
129 }
130
Chris Lattner873ff012009-08-30 05:55:36 +0000131
132 /// Zap - check that the worklist is empty and nuke the backing store for
133 /// the map if it is large.
134 void Zap() {
135 assert(WorklistMap.empty() && "Worklist empty, but map not?");
136
137 // Do an explicit clear, this shrinks the map if needed.
138 WorklistMap.clear();
139 }
140 };
141} // end anonymous namespace.
142
143
144namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000145 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
146 /// just like the normal insertion helper, but also adds any new instructions
147 /// to the instcombine worklist.
148 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
149 InstCombineWorklist &Worklist;
150 public:
151 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152
153 void InsertHelper(Instruction *I, const Twine &Name,
154 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
155 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
156 Worklist.Add(I);
157 }
158 };
159} // end anonymous namespace
160
161
162namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000163 class InstCombiner : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000165 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000166 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000167 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000168 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000169 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000170 InstCombineWorklist Worklist;
171
Chris Lattner74381062009-08-30 07:44:24 +0000172 /// Builder - This is an IRBuilder that automatically inserts new
173 /// instructions into the worklist when they are created.
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000174 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
175 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000176
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000177 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000178 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000179
Owen Andersone922c022009-07-22 00:24:57 +0000180 LLVMContext *Context;
181 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000182
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000183 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000184 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000185
186 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000187
Chris Lattner97e52e42002-04-28 21:27:06 +0000188 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000189 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000190 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000191 }
192
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000193 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000194
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000195 // Visitation implementation - Implement instruction combining for different
196 // instruction types. The semantics are as follows:
197 // Return Value:
198 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000199 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000200 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000201 //
Chris Lattner7e708292002-06-25 16:13:24 +0000202 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000203 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000204 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000205 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000206 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000207 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000208 Instruction *visitURem(BinaryOperator &I);
209 Instruction *visitSRem(BinaryOperator &I);
210 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000211 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000212 Instruction *commonRemTransforms(BinaryOperator &I);
213 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000214 Instruction *commonDivTransforms(BinaryOperator &I);
215 Instruction *commonIDivTransforms(BinaryOperator &I);
216 Instruction *visitUDiv(BinaryOperator &I);
217 Instruction *visitSDiv(BinaryOperator &I);
218 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000219 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000220 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000222 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000223 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000224 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000225 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000226 Instruction *visitOr (BinaryOperator &I);
227 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000228 Instruction *visitShl(BinaryOperator &I);
229 Instruction *visitAShr(BinaryOperator &I);
230 Instruction *visitLShr(BinaryOperator &I);
231 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000232 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000234 Instruction *visitFCmpInst(FCmpInst &I);
235 Instruction *visitICmpInst(ICmpInst &I);
236 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000237 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
238 Instruction *LHS,
239 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000240 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000242
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000243 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000244 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000245 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000246 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000247 Instruction *commonCastTransforms(CastInst &CI);
248 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000249 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000250 Instruction *visitTrunc(TruncInst &CI);
251 Instruction *visitZExt(ZExtInst &CI);
252 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000253 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000254 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000255 Instruction *visitFPToUI(FPToUIInst &FI);
256 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000257 Instruction *visitUIToFP(CastInst &CI);
258 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000259 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000260 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000261 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000262 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000264 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000265 Instruction *visitSelectInst(SelectInst &SI);
266 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000267 Instruction *visitCallInst(CallInst &CI);
268 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000269 Instruction *visitPHINode(PHINode &PN);
270 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000271 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000272 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000273 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000274 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000275 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000276 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000277 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000278 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000279 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000280 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000281
282 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000283 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000284
Chris Lattner9fe38862003-06-19 17:00:31 +0000285 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000286 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000287 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000288 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000289 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000291 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000292 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
293
Chris Lattner9fe38862003-06-19 17:00:31 +0000294
Chris Lattner28977af2004-04-05 01:30:19 +0000295 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000296 // InsertNewInstBefore - insert an instruction New before instruction Old
297 // in the program. Add the new instruction to the worklist.
298 //
Chris Lattner955f3312004-09-28 21:48:02 +0000299 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000300 assert(New && New->getParent() == 0 &&
301 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000302 BasicBlock *BB = Old.getParent();
303 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000304 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000305 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000306 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000307
Chris Lattner8b170942002-08-09 23:47:40 +0000308 // ReplaceInstUsesWith - This method is to be used when an instruction is
309 // found to be dead, replacable with another preexisting expression. Here
310 // we add all uses of I to the worklist, replace all uses of I with the new
311 // value, then return I, so that the inst combiner will know that I was
312 // modified.
313 //
314 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000315 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000316
317 // If we are replacing the instruction with itself, this must be in a
318 // segment of unreachable code, so just clobber the instruction.
319 if (&I == V)
320 V = UndefValue::get(I.getType());
321
322 I.replaceAllUsesWith(V);
323 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000324 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000325
326 // EraseInstFromFunction - When dealing with an instruction that has side
327 // effects or produces a void value, we can't rely on DCE to delete the
328 // instruction. Instead, visit methods should return the value returned by
329 // this function.
330 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000331 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000332
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000333 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000334 // Make sure that we reprocess all operands now that we reduced their
335 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000336 if (I.getNumOperands() < 8) {
337 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338 if (Instruction *Op = dyn_cast<Instruction>(*i))
339 Worklist.Add(Op);
340 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000341 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000342 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000343 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344 return 0; // Don't do anything with FI
345 }
Chris Lattner173234a2008-06-02 01:18:21 +0000346
347 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348 APInt &KnownOne, unsigned Depth = 0) const {
349 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
350 }
351
352 bool MaskedValueIsZero(Value *V, const APInt &Mask,
353 unsigned Depth = 0) const {
354 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
355 }
356 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357 return llvm::ComputeNumSignBits(Op, TD, Depth);
358 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000359
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000360 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000361
Reid Spencere4d87aa2006-12-23 06:05:41 +0000362 /// SimplifyCommutative - This performs a few simplifications for
363 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000364 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000365
Reid Spencere4d87aa2006-12-23 06:05:41 +0000366 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367 /// most-complex to least-complex order.
368 bool SimplifyCompare(CmpInst &I);
369
Chris Lattner886ab6c2009-01-31 08:15:18 +0000370 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371 /// based on the demanded bits.
372 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
373 APInt& KnownZero, APInt& KnownOne,
374 unsigned Depth);
375 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000376 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000377 unsigned Depth=0);
378
379 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380 /// SimplifyDemandedBits knows about. See if the instruction has any
381 /// properties that allow us to simplify its operands.
382 bool SimplifyDemandedInstructionBits(Instruction &Inst);
383
Evan Cheng388df622009-02-03 10:05:09 +0000384 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000386
Chris Lattner5d1704d2009-09-27 19:57:57 +0000387 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
388 // which has a PHI node as operand #0, see if we can fold the instruction
389 // into the PHI (which is only possible if all operands to the PHI are
390 // constants).
Chris Lattner4e998b22004-09-29 05:07:12 +0000391 Instruction *FoldOpIntoPhi(Instruction &I);
392
Chris Lattnerbac32862004-11-14 19:13:23 +0000393 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
394 // operator and they all are only used by the PHI, PHI together their
395 // inputs, and do the operation once, to the result of the PHI.
396 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000397 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000398 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
399
Chris Lattner7da52b22006-11-01 04:51:18 +0000400
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000401 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
402 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000403
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000404 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000405 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000406 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000407 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000408 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000409 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000410 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000411 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000412 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000413
Chris Lattnerafe91a52006-06-15 19:07:26 +0000414
Reid Spencerc55b2432006-12-13 18:21:21 +0000415 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000416
Dan Gohman6de29f82009-06-15 22:12:54 +0000417 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000418 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000419 unsigned GetOrEnforceKnownAlignment(Value *V,
420 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000421
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000422 };
Chris Lattner873ff012009-08-30 05:55:36 +0000423} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000424
Dan Gohman844731a2008-05-13 00:00:25 +0000425char InstCombiner::ID = 0;
426static RegisterPass<InstCombiner>
427X("instcombine", "Combine redundant instructions");
428
Chris Lattner4f98c562003-03-10 21:43:22 +0000429// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000430// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000431static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000432 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000433 if (BinaryOperator::isNeg(V) ||
434 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000435 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000436 return 3;
437 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000438 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000439 if (isa<Argument>(V)) return 3;
440 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000441}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000442
Chris Lattnerc8802d22003-03-11 00:12:48 +0000443// isOnlyUse - Return true if this instruction will be deleted if we stop using
444// it.
445static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000446 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000447}
448
Chris Lattner4cb170c2004-02-23 06:38:22 +0000449// getPromotedType - Return the specified type promoted as it would be to pass
450// though a va_arg area...
451static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000452 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
453 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000454 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000455 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000456 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000457}
458
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000459/// getBitCastOperand - If the specified operand is a CastInst, a constant
460/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
461/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000462static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000463 if (Operator *O = dyn_cast<Operator>(V)) {
464 if (O->getOpcode() == Instruction::BitCast)
465 return O->getOperand(0);
466 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
467 if (GEP->hasAllZeroIndices())
468 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000469 }
Chris Lattnereed48272005-09-13 00:40:14 +0000470 return 0;
471}
472
Reid Spencer3da59db2006-11-27 01:05:10 +0000473/// This function is a wrapper around CastInst::isEliminableCastPair. It
474/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000475static Instruction::CastOps
476isEliminableCastPair(
477 const CastInst *CI, ///< The first cast instruction
478 unsigned opcode, ///< The opcode of the second cast instruction
479 const Type *DstTy, ///< The target type for the second cast instruction
480 TargetData *TD ///< The target data for pointer size
481) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000482
Reid Spencer3da59db2006-11-27 01:05:10 +0000483 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
484 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000485
Reid Spencer3da59db2006-11-27 01:05:10 +0000486 // Get the opcodes of the two Cast instructions
487 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
488 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000489
Chris Lattnera0e69692009-03-24 18:35:40 +0000490 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000491 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000492 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000493
494 // We don't want to form an inttoptr or ptrtoint that converts to an integer
495 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000496 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000497 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000498 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000499 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000500 Res = 0;
501
502 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000503}
504
505/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
506/// in any code being generated. It does not require codegen if V is simple
507/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000508static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
509 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000510 if (V->getType() == Ty || isa<Constant>(V)) return false;
511
Chris Lattner01575b72006-05-25 23:24:33 +0000512 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000513 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000514 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000515 return false;
516 return true;
517}
518
Chris Lattner4f98c562003-03-10 21:43:22 +0000519// SimplifyCommutative - This performs a few simplifications for commutative
520// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000521//
Chris Lattner4f98c562003-03-10 21:43:22 +0000522// 1. Order operands such that they are listed from right (least complex) to
523// left (most complex). This puts constants before unary operators before
524// binary operators.
525//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000526// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
527// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000528//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000529bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000530 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000531 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000532 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000533
Chris Lattner4f98c562003-03-10 21:43:22 +0000534 if (!I.isAssociative()) return Changed;
535 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000536 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
537 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
538 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000539 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000540 cast<Constant>(I.getOperand(1)),
541 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000542 I.setOperand(0, Op->getOperand(0));
543 I.setOperand(1, Folded);
544 return true;
545 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
546 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
547 isOnlyUse(Op) && isOnlyUse(Op1)) {
548 Constant *C1 = cast<Constant>(Op->getOperand(1));
549 Constant *C2 = cast<Constant>(Op1->getOperand(1));
550
551 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000552 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000553 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000554 Op1->getOperand(0),
555 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000556 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 I.setOperand(0, New);
558 I.setOperand(1, Folded);
559 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000560 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000561 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000562 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000563}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000564
Reid Spencere4d87aa2006-12-23 06:05:41 +0000565/// SimplifyCompare - For a CmpInst this function just orders the operands
566/// so that theyare listed from right (least complex) to left (most complex).
567/// This puts constants before unary operators before binary operators.
568bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000569 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000570 return false;
571 I.swapOperands();
572 // Compare instructions are not associative so there's nothing else we can do.
573 return true;
574}
575
Chris Lattner8d969642003-03-10 23:06:50 +0000576// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
577// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000578//
Dan Gohman186a6362009-08-12 16:04:34 +0000579static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000580 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000581 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000582
Chris Lattner0ce85802004-12-14 20:08:06 +0000583 // Constants can be considered to be negated values if they can be folded.
584 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000585 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000586
587 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
588 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000589 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000590
Chris Lattner8d969642003-03-10 23:06:50 +0000591 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000592}
593
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000594// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
595// instruction if the LHS is a constant negative zero (which is the 'negate'
596// form).
597//
Dan Gohman186a6362009-08-12 16:04:34 +0000598static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000599 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000600 return BinaryOperator::getFNegArgument(V);
601
602 // Constants can be considered to be negated values if they can be folded.
603 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000605
606 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
607 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000609
610 return 0;
611}
612
Dan Gohman186a6362009-08-12 16:04:34 +0000613static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000614 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000615 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000616
617 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000618 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000619 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000620 return 0;
621}
622
Chris Lattnerc8802d22003-03-11 00:12:48 +0000623// dyn_castFoldableMul - If this value is a multiply that can be folded into
624// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000625// non-constant operand of the multiply, and set CST to point to the multiplier.
626// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000627//
Dan Gohman186a6362009-08-12 16:04:34 +0000628static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000629 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000630 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000631 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000632 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000633 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000635 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000636 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000637 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000638 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000639 CST = ConstantInt::get(V->getType()->getContext(),
640 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000641 return I->getOperand(0);
642 }
643 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000644 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000645}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000646
Reid Spencer7177c3a2007-03-25 05:33:51 +0000647/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000648static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000649 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000650 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000651}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000652/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000653static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000654 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000655 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000656}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000657/// MultiplyOverflows - True if the multiply can not be expressed in an int
658/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000659static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000660 uint32_t W = C1->getBitWidth();
661 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
662 if (sign) {
663 LHSExt.sext(W * 2);
664 RHSExt.sext(W * 2);
665 } else {
666 LHSExt.zext(W * 2);
667 RHSExt.zext(W * 2);
668 }
669
670 APInt MulExt = LHSExt * RHSExt;
671
672 if (sign) {
673 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
674 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
675 return MulExt.slt(Min) || MulExt.sgt(Max);
676 } else
677 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
678}
Chris Lattner955f3312004-09-28 21:48:02 +0000679
Reid Spencere7816b52007-03-08 01:52:58 +0000680
Chris Lattner255d8912006-02-11 09:31:47 +0000681/// ShrinkDemandedConstant - Check to see if the specified operand of the
682/// specified instruction is a constant integer. If so, check to see if there
683/// are any bits set in the constant that are not demanded. If so, shrink the
684/// constant and return true.
685static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000686 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000687 assert(I && "No instruction?");
688 assert(OpNo < I->getNumOperands() && "Operand index too large");
689
690 // If the operand is not a constant integer, nothing to do.
691 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
692 if (!OpC) return false;
693
694 // If there are no bits set that aren't demanded, nothing to do.
695 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
696 if ((~Demanded & OpC->getValue()) == 0)
697 return false;
698
699 // This instruction is producing bits that are not demanded. Shrink the RHS.
700 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000701 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000702 return true;
703}
704
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000705// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
706// set of known zero and one bits, compute the maximum and minimum values that
707// could have the specified known zero and known one bits, returning them in
708// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000709static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000710 const APInt& KnownOne,
711 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000712 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
713 KnownZero.getBitWidth() == Min.getBitWidth() &&
714 KnownZero.getBitWidth() == Max.getBitWidth() &&
715 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000716 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000717
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000718 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
719 // bit if it is unknown.
720 Min = KnownOne;
721 Max = KnownOne|UnknownBits;
722
Dan Gohman1c8491e2009-04-25 17:12:48 +0000723 if (UnknownBits.isNegative()) { // Sign bit is unknown
724 Min.set(Min.getBitWidth()-1);
725 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000726 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000727}
728
729// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
730// a set of known zero and one bits, compute the maximum and minimum values that
731// could have the specified known zero and known one bits, returning them in
732// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000733static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000736 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
737 KnownZero.getBitWidth() == Min.getBitWidth() &&
738 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000740 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741
742 // The minimum value is when the unknown bits are all zeros.
743 Min = KnownOne;
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
746}
Chris Lattner255d8912006-02-11 09:31:47 +0000747
Chris Lattner886ab6c2009-01-31 08:15:18 +0000748/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
749/// SimplifyDemandedBits knows about. See if the instruction has any
750/// properties that allow us to simplify its operands.
751bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000752 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000753 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
754 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
755
756 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
757 KnownZero, KnownOne, 0);
758 if (V == 0) return false;
759 if (V == &Inst) return true;
760 ReplaceInstUsesWith(Inst, V);
761 return true;
762}
763
764/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
765/// specified instruction operand if possible, updating it in place. It returns
766/// true if it made any change and false otherwise.
767bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
768 APInt &KnownZero, APInt &KnownOne,
769 unsigned Depth) {
770 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
771 KnownZero, KnownOne, Depth);
772 if (NewVal == 0) return false;
773 U.set(NewVal);
774 return true;
775}
776
777
778/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
779/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000780/// that only the bits set in DemandedMask of the result of V are ever used
781/// downstream. Consequently, depending on the mask and V, it may be possible
782/// to replace V with a constant or one of its operands. In such cases, this
783/// function does the replacement and returns true. In all other cases, it
784/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000785/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000786/// to be zero in the expression. These are provided to potentially allow the
787/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
788/// the expression. KnownOne and KnownZero always follow the invariant that
789/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
790/// the bits in KnownOne and KnownZero may only be accurate for those bits set
791/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
792/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000793///
794/// This returns null if it did not change anything and it permits no
795/// simplification. This returns V itself if it did some simplification of V's
796/// operands based on the information about what bits are demanded. This returns
797/// some other non-null value if it found out that V is equal to another value
798/// in the context where the specified bits are demanded, but not for all users.
799Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
800 APInt &KnownZero, APInt &KnownOne,
801 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000802 assert(V != 0 && "Null pointer of Value???");
803 assert(Depth <= 6 && "Limit Search Depth");
804 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000805 const Type *VTy = V->getType();
806 assert((TD || !isa<PointerType>(VTy)) &&
807 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000808 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
809 (!VTy->isIntOrIntVector() ||
810 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000811 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000812 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000813 "Value *V, DemandedMask, KnownZero and KnownOne "
814 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000815 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
816 // We know all of the bits for a constant!
817 KnownOne = CI->getValue() & DemandedMask;
818 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000819 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000820 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000821 if (isa<ConstantPointerNull>(V)) {
822 // We know all of the bits for a constant!
823 KnownOne.clear();
824 KnownZero = DemandedMask;
825 return 0;
826 }
827
Chris Lattner08d2cc72009-01-31 07:26:06 +0000828 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000829 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000830 if (DemandedMask == 0) { // Not demanding any bits from V.
831 if (isa<UndefValue>(V))
832 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000833 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000834 }
835
Chris Lattner4598c942009-01-31 08:24:16 +0000836 if (Depth == 6) // Limit search depth.
837 return 0;
838
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000839 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
840 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
841
Dan Gohman1c8491e2009-04-25 17:12:48 +0000842 Instruction *I = dyn_cast<Instruction>(V);
843 if (!I) {
844 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
845 return 0; // Only analyze instructions.
846 }
847
Chris Lattner4598c942009-01-31 08:24:16 +0000848 // If there are multiple uses of this value and we aren't at the root, then
849 // we can't do any simplifications of the operands, because DemandedMask
850 // only reflects the bits demanded by *one* of the users.
851 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000852 // Despite the fact that we can't simplify this instruction in all User's
853 // context, we can at least compute the knownzero/knownone bits, and we can
854 // do simplifications that apply to *just* the one user if we know that
855 // this instruction has a simpler value in that context.
856 if (I->getOpcode() == Instruction::And) {
857 // If either the LHS or the RHS are Zero, the result is zero.
858 ComputeMaskedBits(I->getOperand(1), DemandedMask,
859 RHSKnownZero, RHSKnownOne, Depth+1);
860 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
861 LHSKnownZero, LHSKnownOne, Depth+1);
862
863 // If all of the demanded bits are known 1 on one side, return the other.
864 // These bits cannot contribute to the result of the 'and' in this
865 // context.
866 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
867 (DemandedMask & ~LHSKnownZero))
868 return I->getOperand(0);
869 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
870 (DemandedMask & ~RHSKnownZero))
871 return I->getOperand(1);
872
873 // If all of the demanded bits in the inputs are known zeros, return zero.
874 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000875 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000876
877 } else if (I->getOpcode() == Instruction::Or) {
878 // We can simplify (X|Y) -> X or Y in the user's context if we know that
879 // only bits from X or Y are demanded.
880
881 // If either the LHS or the RHS are One, the result is One.
882 ComputeMaskedBits(I->getOperand(1), DemandedMask,
883 RHSKnownZero, RHSKnownOne, Depth+1);
884 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
885 LHSKnownZero, LHSKnownOne, Depth+1);
886
887 // If all of the demanded bits are known zero on one side, return the
888 // other. These bits cannot contribute to the result of the 'or' in this
889 // context.
890 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
891 (DemandedMask & ~LHSKnownOne))
892 return I->getOperand(0);
893 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
894 (DemandedMask & ~RHSKnownOne))
895 return I->getOperand(1);
896
897 // If all of the potentially set bits on one side are known to be set on
898 // the other side, just use the 'other' side.
899 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
900 (DemandedMask & (~RHSKnownZero)))
901 return I->getOperand(0);
902 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
903 (DemandedMask & (~LHSKnownZero)))
904 return I->getOperand(1);
905 }
906
Chris Lattner4598c942009-01-31 08:24:16 +0000907 // Compute the KnownZero/KnownOne bits to simplify things downstream.
908 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
909 return 0;
910 }
911
912 // If this is the root being simplified, allow it to have multiple uses,
913 // just set the DemandedMask to all bits so that we can try to simplify the
914 // operands. This allows visitTruncInst (for example) to simplify the
915 // operand of a trunc without duplicating all the logic below.
916 if (Depth == 0 && !V->hasOneUse())
917 DemandedMask = APInt::getAllOnesValue(BitWidth);
918
Reid Spencer8cb68342007-03-12 17:25:59 +0000919 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000920 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000921 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000922 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 case Instruction::And:
924 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000925 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
926 RHSKnownZero, RHSKnownOne, Depth+1) ||
927 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000928 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 return I;
930 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
931 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000932
933 // If all of the demanded bits are known 1 on one side, return the other.
934 // These bits cannot contribute to the result of the 'and'.
935 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
936 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000937 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
939 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000941
942 // If all of the demanded bits in the inputs are known zeros, return zero.
943 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000944 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000945
946 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000947 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000948 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // Output known-1 bits are only known if set in both the LHS & RHS.
951 RHSKnownOne &= LHSKnownOne;
952 // Output known-0 are known to be clear if zero in either the LHS | RHS.
953 RHSKnownZero |= LHSKnownZero;
954 break;
955 case Instruction::Or:
956 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000957 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
958 RHSKnownZero, RHSKnownOne, Depth+1) ||
959 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000960 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 return I;
962 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
963 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // If all of the demanded bits are known zero on one side, return the other.
966 // These bits cannot contribute to the result of the 'or'.
967 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
968 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000969 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000970 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
971 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000973
974 // If all of the potentially set bits on one side are known to be set on
975 // the other side, just use the 'other' side.
976 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
977 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000979 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
980 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000981 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000982
983 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000984 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000986
987 // Output known-0 bits are only known if clear in both the LHS & RHS.
988 RHSKnownZero &= LHSKnownZero;
989 // Output known-1 are known to be set if set in either the LHS | RHS.
990 RHSKnownOne |= LHSKnownOne;
991 break;
992 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1) ||
995 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000996 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I;
998 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
999 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // If all of the demanded bits are known zero on one side, return the other.
1002 // These bits cannot contribute to the result of the 'xor'.
1003 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001004 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001005 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001007
1008 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1009 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1010 (RHSKnownOne & LHSKnownOne);
1011 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1012 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1013 (RHSKnownOne & LHSKnownZero);
1014
1015 // If all of the demanded bits are known to be zero on one side or the
1016 // other, turn this into an *inclusive* or.
1017 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001018 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1019 Instruction *Or =
1020 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1021 I->getName());
1022 return InsertNewInstBefore(Or, *I);
1023 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001024
1025 // If all of the demanded bits on one side are known, and all of the set
1026 // bits on that side are also known to be set on the other side, turn this
1027 // into an AND, as we know the bits will be cleared.
1028 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1029 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1030 // all known
1031 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001032 Constant *AndC = Constant::getIntegerValue(VTy,
1033 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001034 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001035 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001036 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001037 }
1038 }
1039
1040 // If the RHS is a constant, see if we can simplify it.
1041 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001042 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001043 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001044
1045 RHSKnownZero = KnownZeroOut;
1046 RHSKnownOne = KnownOneOut;
1047 break;
1048 }
1049 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001050 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1051 RHSKnownZero, RHSKnownOne, Depth+1) ||
1052 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001053 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 return I;
1055 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1056 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001057
1058 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001059 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1060 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001061 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001062
1063 // Only known if known in both the LHS and RHS.
1064 RHSKnownOne &= LHSKnownOne;
1065 RHSKnownZero &= LHSKnownZero;
1066 break;
1067 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001068 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001069 DemandedMask.zext(truncBf);
1070 RHSKnownZero.zext(truncBf);
1071 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001072 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001073 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001074 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001075 DemandedMask.trunc(BitWidth);
1076 RHSKnownZero.trunc(BitWidth);
1077 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001079 break;
1080 }
1081 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001082 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001084
1085 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1086 if (const VectorType *SrcVTy =
1087 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1088 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1089 // Don't touch a bitcast between vectors of different element counts.
1090 return false;
1091 } else
1092 // Don't touch a scalar-to-vector bitcast.
1093 return false;
1094 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1095 // Don't touch a vector-to-scalar bitcast.
1096 return false;
1097
Chris Lattner886ab6c2009-01-31 08:15:18 +00001098 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001099 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001100 return I;
1101 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001102 break;
1103 case Instruction::ZExt: {
1104 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001105 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001106
Zhou Shengd48653a2007-03-29 04:45:55 +00001107 DemandedMask.trunc(SrcBitWidth);
1108 RHSKnownZero.trunc(SrcBitWidth);
1109 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001111 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001112 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 DemandedMask.zext(BitWidth);
1114 RHSKnownZero.zext(BitWidth);
1115 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001117 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001118 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001119 break;
1120 }
1121 case Instruction::SExt: {
1122 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001123 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001124
Reid Spencer8cb68342007-03-12 17:25:59 +00001125 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001126 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001127
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 // If any of the sign extended bits are demanded, we know that the sign
1130 // bit is demanded.
1131 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001132 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001133
Zhou Shengd48653a2007-03-29 04:45:55 +00001134 InputDemandedBits.trunc(SrcBitWidth);
1135 RHSKnownZero.trunc(SrcBitWidth);
1136 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001139 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 InputDemandedBits.zext(BitWidth);
1141 RHSKnownZero.zext(BitWidth);
1142 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
1145 // If the sign bit of the input is known set or clear, then we know the
1146 // top bits of the result.
1147
1148 // If the input sign bit is known zero, or if the NewBits are not demanded
1149 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001152 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1153 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001154 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001156 }
1157 break;
1158 }
1159 case Instruction::Add: {
1160 // Figure out what the input bits are. If the top bits of the and result
1161 // are not demanded, then the add doesn't demand them from its input
1162 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001164
1165 // If there is a constant on the RHS, there are a variety of xformations
1166 // we can do.
1167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168 // If null, this should be simplified elsewhere. Some of the xforms here
1169 // won't work if the RHS is zero.
1170 if (RHS->isZero())
1171 break;
1172
1173 // If the top bit of the output is demanded, demand everything from the
1174 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001175 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001176
1177 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001178 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001179 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001180 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001181
1182 // If the RHS of the add has bits set that can't affect the input, reduce
1183 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001184 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001185 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
1187 // Avoid excess work.
1188 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1189 break;
1190
1191 // Turn it into OR if input bits are zero.
1192 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1193 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001194 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001197 }
1198
1199 // We can say something about the output known-zero and known-one bits,
1200 // depending on potential carries from the input constant and the
1201 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1202 // bits set and the RHS constant is 0x01001, then we know we have a known
1203 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1204
1205 // To compute this, we first compute the potential carry bits. These are
1206 // the bits which may be modified. I'm not aware of a better way to do
1207 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001208 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001209 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001210
1211 // Now that we know which bits have carries, compute the known-1/0 sets.
1212
1213 // Bits are known one if they are known zero in one operand and one in the
1214 // other, and there is no input carry.
1215 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1216 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1217
1218 // Bits are known zero if they are known zero in both operands and there
1219 // is no input carry.
1220 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1221 } else {
1222 // If the high-bits of this ADD are not demanded, then it does not demand
1223 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001224 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001225 // Right fill the mask of bits for this ADD to demand the most
1226 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001227 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1229 LHSKnownZero, LHSKnownOne, Depth+1) ||
1230 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001233 }
1234 }
1235 break;
1236 }
1237 case Instruction::Sub:
1238 // If the high-bits of this SUB are not demanded, then it does not demand
1239 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001240 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 // Right fill the mask of bits for this SUB to demand the most
1242 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001243 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1246 LHSKnownZero, LHSKnownOne, Depth+1) ||
1247 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001248 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001250 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001251 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1252 // the known zeros and ones.
1253 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 break;
1255 case Instruction::Shl:
1256 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001257 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001258 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001259 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 return I;
1262 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001263 RHSKnownZero <<= ShiftAmt;
1264 RHSKnownOne <<= ShiftAmt;
1265 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001266 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001267 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001268 }
1269 break;
1270 case Instruction::LShr:
1271 // For a logical shift right
1272 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001273 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001274
Reid Spencer8cb68342007-03-12 17:25:59 +00001275 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001277 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001279 return I;
1280 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001281 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1282 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001283 if (ShiftAmt) {
1284 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001285 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001286 RHSKnownZero |= HighBits; // high bits known zero.
1287 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 }
1289 break;
1290 case Instruction::AShr:
1291 // If this is an arithmetic shift right and only the low-bit is set, we can
1292 // always convert this into a logical shr, even if the shift amount is
1293 // variable. The low bit of the shift cannot be an input sign bit unless
1294 // the shift amount is >= the size of the datatype, which is undefined.
1295 if (DemandedMask == 1) {
1296 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001297 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001299 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001301
1302 // If the sign bit is the only bit demanded by this ashr, then there is no
1303 // need to do it, the shift doesn't change the high bit.
1304 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001305 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001306
1307 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001308 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001309
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001311 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001312 // If any of the "high bits" are demanded, we should set the sign bit as
1313 // demanded.
1314 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1315 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001318 return I;
1319 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001321 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001322 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1323 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1324
1325 // Handle the sign bits.
1326 APInt SignBit(APInt::getSignBit(BitWidth));
1327 // Adjust to where it is now in the mask.
1328 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1329
1330 // If the input sign bit is known to be zero, or if none of the top bits
1331 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001332 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 (HighBits & ~DemandedMask) == HighBits) {
1334 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001338 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1339 RHSKnownOne |= HighBits;
1340 }
1341 }
1342 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001343 case Instruction::SRem:
1344 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001345 APInt RA = Rem->getValue().abs();
1346 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001347 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001349
Nick Lewycky8e394322008-11-02 02:41:50 +00001350 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001351 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001354 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355
1356 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1357 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001358
1359 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001360
Chris Lattner886ab6c2009-01-31 08:15:18 +00001361 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 }
1363 }
1364 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001365 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001366 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1367 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001368 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1369 KnownZero2, KnownOne2, Depth+1) ||
1370 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001371 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001372 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001373
Chris Lattner455e9ab2009-01-21 18:09:24 +00001374 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001375 Leaders = std::max(Leaders,
1376 KnownZero2.countLeadingOnes());
1377 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001378 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001379 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001380 case Instruction::Call:
1381 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1382 switch (II->getIntrinsicID()) {
1383 default: break;
1384 case Intrinsic::bswap: {
1385 // If the only bits demanded come from one byte of the bswap result,
1386 // just shift the input byte into position to eliminate the bswap.
1387 unsigned NLZ = DemandedMask.countLeadingZeros();
1388 unsigned NTZ = DemandedMask.countTrailingZeros();
1389
1390 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1391 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1392 // have 14 leading zeros, round to 8.
1393 NLZ &= ~7;
1394 NTZ &= ~7;
1395 // If we need exactly one byte, we can do this transformation.
1396 if (BitWidth-NLZ-NTZ == 8) {
1397 unsigned ResultBit = NTZ;
1398 unsigned InputBit = BitWidth-NTZ-8;
1399
1400 // Replace this with either a left or right shift to get the byte into
1401 // the right place.
1402 Instruction *NewVal;
1403 if (InputBit > ResultBit)
1404 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001405 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001406 else
1407 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001408 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001409 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001410 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001411 }
1412
1413 // TODO: Could compute known zero/one bits based on the input.
1414 break;
1415 }
1416 }
1417 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001418 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001419 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001420 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001421
1422 // If the client is only demanding bits that we know, return the known
1423 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001424 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1425 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001426 return false;
1427}
1428
Chris Lattner867b99f2006-10-05 06:55:50 +00001429
Mon P Wangaeb06d22008-11-10 04:46:22 +00001430/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001431/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001432/// actually used by the caller. This method analyzes which elements of the
1433/// operand are undef and returns that information in UndefElts.
1434///
1435/// If the information about demanded elements can be used to simplify the
1436/// operation, the operation is simplified, then the resultant value is
1437/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001438Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1439 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001440 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001441 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001442 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001443 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001444
1445 if (isa<UndefValue>(V)) {
1446 // If the entire vector is undefined, just return this info.
1447 UndefElts = EltMask;
1448 return 0;
1449 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1450 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001451 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001452 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001453
Chris Lattner867b99f2006-10-05 06:55:50 +00001454 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001455 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1456 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001457 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458
1459 std::vector<Constant*> Elts;
1460 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001461 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001463 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1465 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001466 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 } else { // Otherwise, defined.
1468 Elts.push_back(CP->getOperand(i));
1469 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001470
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001472 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 return NewCP != CP ? NewCP : 0;
1474 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001475 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001477
1478 // Check if this is identity. If so, return 0 since we are not simplifying
1479 // anything.
1480 if (DemandedElts == ((1ULL << VWidth) -1))
1481 return 0;
1482
Reid Spencer9d6565a2007-02-15 02:26:10 +00001483 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001484 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001485 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001487 for (unsigned i = 0; i != VWidth; ++i) {
1488 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1489 Elts.push_back(Elt);
1490 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001491 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001492 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001493 }
1494
Dan Gohman488fbfc2008-09-09 18:11:14 +00001495 // Limit search depth.
1496 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001497 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001498
1499 // If multiple users are using the root value, procede with
1500 // simplification conservatively assuming that all elements
1501 // are needed.
1502 if (!V->hasOneUse()) {
1503 // Quit if we find multiple users of a non-root value though.
1504 // They'll be handled when it's their turn to be visited by
1505 // the main instcombine process.
1506 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001507 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001508 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001509
1510 // Conservatively assume that all elements are needed.
1511 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001512 }
1513
1514 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001515 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001516
1517 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001518 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001519 Value *TmpV;
1520 switch (I->getOpcode()) {
1521 default: break;
1522
1523 case Instruction::InsertElement: {
1524 // If this is a variable index, we don't know which element it overwrites.
1525 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001526 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001527 if (Idx == 0) {
1528 // Note that we can't propagate undef elt info, because we don't know
1529 // which elt is getting updated.
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1531 UndefElts2, Depth+1);
1532 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1533 break;
1534 }
1535
1536 // If this is inserting an element that isn't demanded, remove this
1537 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001538 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001539 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1540 Worklist.Add(I);
1541 return I->getOperand(0);
1542 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001543
1544 // Otherwise, the element inserted overwrites whatever was there, so the
1545 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001546 APInt DemandedElts2 = DemandedElts;
1547 DemandedElts2.clear(IdxNo);
1548 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001549 UndefElts, Depth+1);
1550 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1551
1552 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001553 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 break;
1555 }
1556 case Instruction::ShuffleVector: {
1557 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001558 uint64_t LHSVWidth =
1559 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001560 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001561 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001562 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001563 unsigned MaskVal = Shuffle->getMaskValue(i);
1564 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001565 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001566 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001567 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001568 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 else
Evan Cheng388df622009-02-03 10:05:09 +00001570 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 }
1572 }
1573 }
1574
Nate Begeman7b254672009-02-11 22:36:25 +00001575 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001577 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001578 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1579
Nate Begeman7b254672009-02-11 22:36:25 +00001580 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1582 UndefElts3, Depth+1);
1583 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1584
1585 bool NewUndefElts = false;
1586 for (unsigned i = 0; i < VWidth; i++) {
1587 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001588 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001589 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001590 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001591 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001592 NewUndefElts = true;
1593 UndefElts.set(i);
1594 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001595 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001596 if (UndefElts3[MaskVal - LHSVWidth]) {
1597 NewUndefElts = true;
1598 UndefElts.set(i);
1599 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 }
1601 }
1602
1603 if (NewUndefElts) {
1604 // Add additional discovered undefs.
1605 std::vector<Constant*> Elts;
1606 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001607 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001608 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001609 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001610 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001611 Shuffle->getMaskValue(i)));
1612 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001613 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001614 MadeChange = true;
1615 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001616 break;
1617 }
Chris Lattner69878332007-04-14 22:29:23 +00001618 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001619 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001620 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1621 if (!VTy) break;
1622 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001623 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001624 unsigned Ratio;
1625
1626 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001627 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001628 // elements as are demanded of us.
1629 Ratio = 1;
1630 InputDemandedElts = DemandedElts;
1631 } else if (VWidth > InVWidth) {
1632 // Untested so far.
1633 break;
1634
1635 // If there are more elements in the result than there are in the source,
1636 // then an input element is live if any of the corresponding output
1637 // elements are live.
1638 Ratio = VWidth/InVWidth;
1639 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001640 if (DemandedElts[OutIdx])
1641 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001642 }
1643 } else {
1644 // Untested so far.
1645 break;
1646
1647 // If there are more elements in the source than there are in the result,
1648 // then an input element is live if the corresponding output element is
1649 // live.
1650 Ratio = InVWidth/VWidth;
1651 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001652 if (DemandedElts[InIdx/Ratio])
1653 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001654 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001655
Chris Lattner69878332007-04-14 22:29:23 +00001656 // div/rem demand all inputs, because they don't want divide by zero.
1657 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1658 UndefElts2, Depth+1);
1659 if (TmpV) {
1660 I->setOperand(0, TmpV);
1661 MadeChange = true;
1662 }
1663
1664 UndefElts = UndefElts2;
1665 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001666 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001667 // If there are more elements in the result than there are in the source,
1668 // then an output element is undef if the corresponding input element is
1669 // undef.
1670 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001671 if (UndefElts2[OutIdx/Ratio])
1672 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001673 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001674 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001675 // If there are more elements in the source than there are in the result,
1676 // then a result element is undef if all of the corresponding input
1677 // elements are undef.
1678 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1679 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001680 if (!UndefElts2[InIdx]) // Not undef?
1681 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001682 }
1683 break;
1684 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001685 case Instruction::And:
1686 case Instruction::Or:
1687 case Instruction::Xor:
1688 case Instruction::Add:
1689 case Instruction::Sub:
1690 case Instruction::Mul:
1691 // div/rem demand all inputs, because they don't want divide by zero.
1692 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1693 UndefElts, Depth+1);
1694 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1695 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1696 UndefElts2, Depth+1);
1697 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1698
1699 // Output elements are undefined if both are undefined. Consider things
1700 // like undef&0. The result is known zero, not undef.
1701 UndefElts &= UndefElts2;
1702 break;
1703
1704 case Instruction::Call: {
1705 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1706 if (!II) break;
1707 switch (II->getIntrinsicID()) {
1708 default: break;
1709
1710 // Binary vector operations that work column-wise. A dest element is a
1711 // function of the corresponding input elements from the two inputs.
1712 case Intrinsic::x86_sse_sub_ss:
1713 case Intrinsic::x86_sse_mul_ss:
1714 case Intrinsic::x86_sse_min_ss:
1715 case Intrinsic::x86_sse_max_ss:
1716 case Intrinsic::x86_sse2_sub_sd:
1717 case Intrinsic::x86_sse2_mul_sd:
1718 case Intrinsic::x86_sse2_min_sd:
1719 case Intrinsic::x86_sse2_max_sd:
1720 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1721 UndefElts, Depth+1);
1722 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1723 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1724 UndefElts2, Depth+1);
1725 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1726
1727 // If only the low elt is demanded and this is a scalarizable intrinsic,
1728 // scalarize it now.
1729 if (DemandedElts == 1) {
1730 switch (II->getIntrinsicID()) {
1731 default: break;
1732 case Intrinsic::x86_sse_sub_ss:
1733 case Intrinsic::x86_sse_mul_ss:
1734 case Intrinsic::x86_sse2_sub_sd:
1735 case Intrinsic::x86_sse2_mul_sd:
1736 // TODO: Lower MIN/MAX/ABS/etc
1737 Value *LHS = II->getOperand(1);
1738 Value *RHS = II->getOperand(2);
1739 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001740 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001741 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001742 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001743 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001744
1745 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001746 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001747 case Intrinsic::x86_sse_sub_ss:
1748 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001749 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001750 II->getName()), *II);
1751 break;
1752 case Intrinsic::x86_sse_mul_ss:
1753 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001754 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 II->getName()), *II);
1756 break;
1757 }
1758
1759 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001760 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001761 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001762 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001763 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001764 return New;
1765 }
1766 }
1767
1768 // Output elements are undefined if both are undefined. Consider things
1769 // like undef&0. The result is known zero, not undef.
1770 UndefElts &= UndefElts2;
1771 break;
1772 }
1773 break;
1774 }
1775 }
1776 return MadeChange ? I : 0;
1777}
1778
Dan Gohman45b4e482008-05-19 22:14:15 +00001779
Chris Lattner564a7272003-08-13 19:01:45 +00001780/// AssociativeOpt - Perform an optimization on an associative operator. This
1781/// function is designed to check a chain of associative operators for a
1782/// potential to apply a certain optimization. Since the optimization may be
1783/// applicable if the expression was reassociated, this checks the chain, then
1784/// reassociates the expression as necessary to expose the optimization
1785/// opportunity. This makes use of a special Functor, which must define
1786/// 'shouldApply' and 'apply' methods.
1787///
1788template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001789static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001790 unsigned Opcode = Root.getOpcode();
1791 Value *LHS = Root.getOperand(0);
1792
1793 // Quick check, see if the immediate LHS matches...
1794 if (F.shouldApply(LHS))
1795 return F.apply(Root);
1796
1797 // Otherwise, if the LHS is not of the same opcode as the root, return.
1798 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001799 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001800 // Should we apply this transform to the RHS?
1801 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1802
1803 // If not to the RHS, check to see if we should apply to the LHS...
1804 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1805 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1806 ShouldApply = true;
1807 }
1808
1809 // If the functor wants to apply the optimization to the RHS of LHSI,
1810 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1811 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001812 // Now all of the instructions are in the current basic block, go ahead
1813 // and perform the reassociation.
1814 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1815
1816 // First move the selected RHS to the LHS of the root...
1817 Root.setOperand(0, LHSI->getOperand(1));
1818
1819 // Make what used to be the LHS of the root be the user of the root...
1820 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001821 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001822 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001823 return 0;
1824 }
Chris Lattner65725312004-04-16 18:08:07 +00001825 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001826 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001827 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001828 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001829 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001830
1831 // Now propagate the ExtraOperand down the chain of instructions until we
1832 // get to LHSI.
1833 while (TmpLHSI != LHSI) {
1834 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001835 // Move the instruction to immediately before the chain we are
1836 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001837 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001838 ARI = NextLHSI;
1839
Chris Lattner564a7272003-08-13 19:01:45 +00001840 Value *NextOp = NextLHSI->getOperand(1);
1841 NextLHSI->setOperand(1, ExtraOperand);
1842 TmpLHSI = NextLHSI;
1843 ExtraOperand = NextOp;
1844 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001845
Chris Lattner564a7272003-08-13 19:01:45 +00001846 // Now that the instructions are reassociated, have the functor perform
1847 // the transformation...
1848 return F.apply(Root);
1849 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1852 }
1853 return 0;
1854}
1855
Dan Gohman844731a2008-05-13 00:00:25 +00001856namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001857
Nick Lewycky02d639f2008-05-23 04:34:58 +00001858// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001859struct AddRHS {
1860 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001861 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001862 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1863 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001864 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001865 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001866 }
1867};
1868
1869// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1870// iff C1&C2 == 0
1871struct AddMaskingAnd {
1872 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001873 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001874 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001875 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001876 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001877 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001878 }
1879 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001880 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001881 }
1882};
1883
Dan Gohman844731a2008-05-13 00:00:25 +00001884}
1885
Chris Lattner6e7ba452005-01-01 16:22:27 +00001886static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001887 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001888 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001889 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001890
Chris Lattner2eefe512004-04-09 19:05:30 +00001891 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001892 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1893 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001894
Chris Lattner2eefe512004-04-09 19:05:30 +00001895 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1896 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001897 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1898 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001899 }
1900
1901 Value *Op0 = SO, *Op1 = ConstOperand;
1902 if (!ConstIsRHS)
1903 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001904
Chris Lattner6e7ba452005-01-01 16:22:27 +00001905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001906 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1907 SO->getName()+".op");
1908 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1909 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1910 SO->getName()+".cmp");
1911 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1912 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1913 SO->getName()+".cmp");
1914 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001915}
1916
1917// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1918// constant as the other operand, try to fold the binary operator into the
1919// select arguments. This also works for Cast instructions, which obviously do
1920// not have a second operand.
1921static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1922 InstCombiner *IC) {
1923 // Don't modify shared select instructions
1924 if (!SI->hasOneUse()) return 0;
1925 Value *TV = SI->getOperand(1);
1926 Value *FV = SI->getOperand(2);
1927
1928 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001929 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001930 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001931
Chris Lattner6e7ba452005-01-01 16:22:27 +00001932 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1933 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1934
Gabor Greif051a9502008-04-06 20:25:17 +00001935 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1936 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001937 }
1938 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001939}
1940
Chris Lattner4e998b22004-09-29 05:07:12 +00001941
Chris Lattner5d1704d2009-09-27 19:57:57 +00001942/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1943/// has a PHI node as operand #0, see if we can fold the instruction into the
1944/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner4e998b22004-09-29 05:07:12 +00001945Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1946 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001947 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001948 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001949
Chris Lattner5d1704d2009-09-27 19:57:57 +00001950 // Check to see if all of the operands of the PHI are simple constants
1951 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001952 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1953 // bail out. We don't do arbitrary constant expressions here because moving
1954 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001955 BasicBlock *NonConstBB = 0;
1956 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00001957 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1958 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001960 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 NonConstBB = PN->getIncomingBlock(i);
1962
1963 // If the incoming non-constant value is in I's block, we have an infinite
1964 // loop.
1965 if (NonConstBB == I.getParent())
1966 return 0;
1967 }
1968
1969 // If there is exactly one non-constant value, we can insert a copy of the
1970 // operation in that block. However, if this is a critical edge, we would be
1971 // inserting the computation one some other paths (e.g. inside a loop). Only
1972 // do this if the pred block is unconditionally branching into the phi block.
1973 if (NonConstBB) {
1974 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1975 if (!BI || !BI->isUnconditional()) return 0;
1976 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001977
1978 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001979 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001980 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001981 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001982 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001983
1984 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00001985 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
1986 // We only currently try to fold the condition of a select when it is a phi,
1987 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001988 Value *TrueV = SI->getTrueValue();
1989 Value *FalseV = SI->getFalseValue();
Chris Lattner5d1704d2009-09-27 19:57:57 +00001990 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001991 BasicBlock *ThisBB = PN->getIncomingBlock(i);
1992 Value *TrueVInPred = TrueV->DoPHITranslation(I.getParent(), ThisBB);
1993 Value *FalseVInPred = FalseV->DoPHITranslation(I.getParent(), ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00001994 Value *InV = 0;
1995 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001996 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00001997 } else {
1998 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001999 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2000 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002001 "phitmp", NonConstBB->getTerminator());
2002 Worklist.Add(cast<Instruction>(InV));
2003 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002004 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002005 }
2006 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002007 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002008 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002009 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002010 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002012 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002013 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002014 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015 } else {
2016 assert(PN->getIncomingBlock(i) == NonConstBB);
2017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002018 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002019 PN->getIncomingValue(i), C, "phitmp",
2020 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002021 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002022 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002023 CI->getPredicate(),
2024 PN->getIncomingValue(i), C, "phitmp",
2025 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002026 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002027 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028
Chris Lattner7a1e9242009-08-30 06:13:40 +00002029 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002030 }
2031 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002032 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002033 } else {
2034 CastInst *CI = cast<CastInst>(&I);
2035 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002036 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002037 Value *InV;
2038 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002039 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002040 } else {
2041 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002042 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002043 I.getType(), "phitmp",
2044 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002045 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002046 }
2047 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002048 }
2049 }
2050 return ReplaceInstUsesWith(I, NewPN);
2051}
2052
Chris Lattner2454a2e2008-01-29 06:52:45 +00002053
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002054/// WillNotOverflowSignedAdd - Return true if we can prove that:
2055/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2056/// This basically requires proving that the add in the original type would not
2057/// overflow to change the sign bit or have a carry out.
2058bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2059 // There are different heuristics we can use for this. Here are some simple
2060 // ones.
2061
2062 // Add has the property that adding any two 2's complement numbers can only
2063 // have one carry bit which can change a sign. As such, if LHS and RHS each
2064 // have at least two sign bits, we know that the addition of the two values will
2065 // sign extend fine.
2066 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2067 return true;
2068
2069
2070 // If one of the operands only has one non-zero bit, and if the other operand
2071 // has a known-zero bit in a more significant place than it (not including the
2072 // sign bit) the ripple may go up to and fill the zero, but won't change the
2073 // sign. For example, (X & ~4) + 1.
2074
2075 // TODO: Implement.
2076
2077 return false;
2078}
2079
Chris Lattner2454a2e2008-01-29 06:52:45 +00002080
Chris Lattner7e708292002-06-25 16:13:24 +00002081Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002082 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002083 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002084
Chris Lattner66331a42004-04-10 22:01:55 +00002085 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002086 // X + undef -> undef
2087 if (isa<UndefValue>(RHS))
2088 return ReplaceInstUsesWith(I, RHS);
2089
Chris Lattner66331a42004-04-10 22:01:55 +00002090 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002091 if (RHSC->isNullValue())
2092 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002093
Chris Lattner66331a42004-04-10 22:01:55 +00002094 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002095 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002096 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002097 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002098 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002099 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002100
2101 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2102 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002103 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002104 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002105
Eli Friedman709b33d2009-07-13 22:27:52 +00002106 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002107 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002108 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002109 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002110 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002111
2112 if (isa<PHINode>(LHS))
2113 if (Instruction *NV = FoldOpIntoPhi(I))
2114 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002115
Chris Lattner4f637d42006-01-06 17:59:59 +00002116 ConstantInt *XorRHS = 0;
2117 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002118 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002119 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002120 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002121 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002122
Zhou Sheng4351c642007-04-02 08:20:41 +00002123 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002124 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2125 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002126 do {
2127 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002128 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2129 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002130 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2131 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002132 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002133 if (!MaskedValueIsZero(XorLHS,
2134 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002135 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002136 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002137 }
2138 }
2139 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002140 C0080Val = APIntOps::lshr(C0080Val, Size);
2141 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2142 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002143
Reid Spencer35c38852007-03-28 01:36:16 +00002144 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002145 // with funny bit widths then this switch statement should be removed. It
2146 // is just here to get the size of the "middle" type back up to something
2147 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002148 const Type *MiddleType = 0;
2149 switch (Size) {
2150 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002151 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2152 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2153 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002154 }
2155 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002156 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002157 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002158 }
2159 }
Chris Lattner66331a42004-04-10 22:01:55 +00002160 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002161
Owen Anderson1d0be152009-08-13 21:58:54 +00002162 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002163 return BinaryOperator::CreateXor(LHS, RHS);
2164
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002165 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002166 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002167 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002168 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002169
2170 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2171 if (RHSI->getOpcode() == Instruction::Sub)
2172 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2173 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2174 }
2175 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2176 if (LHSI->getOpcode() == Instruction::Sub)
2177 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2178 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2179 }
Robert Bocchino71698282004-07-27 21:02:21 +00002180 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002181
Chris Lattner5c4afb92002-05-08 22:46:53 +00002182 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002183 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002185 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002186 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002187 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002188 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002189 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002190 }
2191
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002192 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002193 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002194
2195 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002196 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002197 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002198 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002199
Misha Brukmanfd939082005-04-21 23:48:37 +00002200
Chris Lattner50af16a2004-11-13 19:50:12 +00002201 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002202 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002203 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002204 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002205
2206 // X*C1 + X*C2 --> X * (C1+C2)
2207 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002208 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002209 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002210 }
2211
2212 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002213 if (dyn_castFoldableMul(RHS, C2) == LHS)
2214 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002215
Chris Lattnere617c9e2007-01-05 02:17:46 +00002216 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002217 if (dyn_castNotVal(LHS) == RHS ||
2218 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002219 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002220
Chris Lattnerad3448c2003-02-18 19:57:07 +00002221
Chris Lattner564a7272003-08-13 19:01:45 +00002222 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002223 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2224 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002225 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002226
2227 // A+B --> A|B iff A and B have no bits set in common.
2228 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230 APInt LHSKnownOne(IT->getBitWidth(), 0);
2231 APInt LHSKnownZero(IT->getBitWidth(), 0);
2232 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233 if (LHSKnownZero != 0) {
2234 APInt RHSKnownOne(IT->getBitWidth(), 0);
2235 APInt RHSKnownZero(IT->getBitWidth(), 0);
2236 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237
2238 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002239 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002240 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002241 }
2242 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002243
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002244 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002245 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002246 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002247 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2248 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002249 if (W != Y) {
2250 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002251 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002252 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002253 std::swap(W, X);
2254 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002255 std::swap(Y, Z);
2256 std::swap(W, X);
2257 }
2258 }
2259
2260 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002261 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002262 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002263 }
2264 }
2265 }
2266
Chris Lattner6b032052003-10-02 15:11:26 +00002267 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002268 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002269 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002270 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002271
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002272 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002273 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002274 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002275 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002276 if (Anded == CRHS) {
2277 // See if all bits from the first bit set in the Add RHS up are included
2278 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002279 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002280
2281 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002282 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002283
2284 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002285 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002286
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002287 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2288 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002289 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002290 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002291 }
2292 }
2293 }
2294
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002295 // Try to fold constant add into select arguments.
2296 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002297 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002298 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002299 }
2300
Chris Lattner42790482007-12-20 01:56:58 +00002301 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002302 {
2303 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002304 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002305 if (!SI) {
2306 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002307 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002308 }
Chris Lattner42790482007-12-20 01:56:58 +00002309 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002310 Value *TV = SI->getTrueValue();
2311 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002312 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002313
2314 // Can we fold the add into the argument of the select?
2315 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002316 if (match(FV, m_Zero()) &&
2317 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002318 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002319 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002320 if (match(TV, m_Zero()) &&
2321 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002322 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002323 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002324 }
2325 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002326
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002327 // Check for (add (sext x), y), see if we can merge this into an
2328 // integer add followed by a sext.
2329 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2330 // (add (sext x), cst) --> (sext (add x, cst'))
2331 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2332 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002333 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002334 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002335 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002336 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2337 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002338 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2339 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002340 return new SExtInst(NewAdd, I.getType());
2341 }
2342 }
2343
2344 // (add (sext x), (sext y)) --> (sext (add int x, y))
2345 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2346 // Only do this if x/y have the same type, if at last one of them has a
2347 // single use (so we don't increase the number of sexts), and if the
2348 // integer add will not overflow.
2349 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2350 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2351 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2352 RHSConv->getOperand(0))) {
2353 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002354 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2355 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002356 return new SExtInst(NewAdd, I.getType());
2357 }
2358 }
2359 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002360
2361 return Changed ? &I : 0;
2362}
2363
2364Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2365 bool Changed = SimplifyCommutative(I);
2366 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2367
2368 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2369 // X + 0 --> X
2370 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002371 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002372 (I.getType())->getValueAPF()))
2373 return ReplaceInstUsesWith(I, LHS);
2374 }
2375
2376 if (isa<PHINode>(LHS))
2377 if (Instruction *NV = FoldOpIntoPhi(I))
2378 return NV;
2379 }
2380
2381 // -A + B --> B - A
2382 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002383 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002384 return BinaryOperator::CreateFSub(RHS, LHSV);
2385
2386 // A + -B --> A - B
2387 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002388 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002389 return BinaryOperator::CreateFSub(LHS, V);
2390
2391 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2392 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2393 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2394 return ReplaceInstUsesWith(I, LHS);
2395
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002396 // Check for (add double (sitofp x), y), see if we can merge this into an
2397 // integer add followed by a promotion.
2398 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2399 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2400 // ... if the constant fits in the integer value. This is useful for things
2401 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2402 // requires a constant pool load, and generally allows the add to be better
2403 // instcombined.
2404 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2405 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002406 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002407 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002408 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002409 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2410 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002411 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2412 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002413 return new SIToFPInst(NewAdd, I.getType());
2414 }
2415 }
2416
2417 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2418 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2419 // Only do this if x/y have the same type, if at last one of them has a
2420 // single use (so we don't increase the number of int->fp conversions),
2421 // and if the integer add will not overflow.
2422 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2423 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2424 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2425 RHSConv->getOperand(0))) {
2426 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002427 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2428 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002429 return new SIToFPInst(NewAdd, I.getType());
2430 }
2431 }
2432 }
2433
Chris Lattner7e708292002-06-25 16:13:24 +00002434 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002435}
2436
Chris Lattner7e708292002-06-25 16:13:24 +00002437Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002438 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002439
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002440 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002441 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002442
Chris Lattner233f7dc2002-08-12 21:17:25 +00002443 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002444 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002445 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002446
Chris Lattnere87597f2004-10-16 18:11:37 +00002447 if (isa<UndefValue>(Op0))
2448 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2449 if (isa<UndefValue>(Op1))
2450 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2451
Chris Lattnerd65460f2003-11-05 01:06:05 +00002452 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2453 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002454 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002455 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002456
Chris Lattnerd65460f2003-11-05 01:06:05 +00002457 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002458 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002459 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002460 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002461
Chris Lattner76b7a062007-01-15 07:02:54 +00002462 // -(X >>u 31) -> (X >>s 31)
2463 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002464 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002465 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002466 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002467 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002468 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002469 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002470 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002471 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002472 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002473 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002474 }
2475 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002476 }
2477 else if (SI->getOpcode() == Instruction::AShr) {
2478 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2479 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002480 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002481 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002482 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002483 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002484 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002485 }
2486 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002487 }
2488 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002489 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002490
2491 // Try to fold constant sub into select arguments.
2492 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002493 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002494 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002495
2496 // C - zext(bool) -> bool ? C - 1 : C
2497 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002498 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002499 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002500 }
2501
Owen Anderson1d0be152009-08-13 21:58:54 +00002502 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002503 return BinaryOperator::CreateXor(Op0, Op1);
2504
Chris Lattner43d84d62005-04-07 16:15:25 +00002505 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002506 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002507 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002508 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002509 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002510 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002511 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002512 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002513 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2514 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2515 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002516 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002517 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002518 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002519 }
2520
Chris Lattnerfd059242003-10-15 16:48:29 +00002521 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002522 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2523 // is not used by anyone else...
2524 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002525 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002526 // Swap the two operands of the subexpr...
2527 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2528 Op1I->setOperand(0, IIOp1);
2529 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002530
Chris Lattnera2881962003-02-18 19:28:33 +00002531 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002532 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002533 }
2534
2535 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2536 //
2537 if (Op1I->getOpcode() == Instruction::And &&
2538 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2539 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2540
Chris Lattner74381062009-08-30 07:44:24 +00002541 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002542 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002543 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002544
Reid Spencerac5209e2006-10-16 23:08:08 +00002545 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002546 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002547 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002548 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002549 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002550 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002551 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002552
Chris Lattnerad3448c2003-02-18 19:57:07 +00002553 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002554 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002555 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002556 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002557 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002558 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002559 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002560 }
Chris Lattner40371712002-05-09 01:29:19 +00002561 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002562 }
Chris Lattnera2881962003-02-18 19:28:33 +00002563
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002564 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2565 if (Op0I->getOpcode() == Instruction::Add) {
2566 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2567 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2568 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2569 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2570 } else if (Op0I->getOpcode() == Instruction::Sub) {
2571 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002572 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002573 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002574 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002575 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002576
Chris Lattner50af16a2004-11-13 19:50:12 +00002577 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002578 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002579 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002580 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002581
Chris Lattner50af16a2004-11-13 19:50:12 +00002582 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002583 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002584 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002585 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002586 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002587}
2588
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002589Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2590 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2591
2592 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002593 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002594 return BinaryOperator::CreateFAdd(Op0, V);
2595
2596 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2597 if (Op1I->getOpcode() == Instruction::FAdd) {
2598 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002599 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002600 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002601 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002602 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002603 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002604 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002605 }
2606
2607 return 0;
2608}
2609
Chris Lattnera0141b92007-07-15 20:42:37 +00002610/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2611/// comparison only checks the sign bit. If it only checks the sign bit, set
2612/// TrueIfSigned if the result of the comparison is true when the input value is
2613/// signed.
2614static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2615 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002616 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002617 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2618 TrueIfSigned = true;
2619 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002620 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2621 TrueIfSigned = true;
2622 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002623 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2624 TrueIfSigned = false;
2625 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002626 case ICmpInst::ICMP_UGT:
2627 // True if LHS u> RHS and RHS == high-bit-mask - 1
2628 TrueIfSigned = true;
2629 return RHS->getValue() ==
2630 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2631 case ICmpInst::ICMP_UGE:
2632 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2633 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002634 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002635 default:
2636 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002637 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002638}
2639
Chris Lattner7e708292002-06-25 16:13:24 +00002640Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002641 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002642 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002643
Eli Friedman1694e092009-07-18 09:12:15 +00002644 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002645 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002646
Chris Lattner233f7dc2002-08-12 21:17:25 +00002647 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002648 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2649 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002650
2651 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002652 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002653 if (SI->getOpcode() == Instruction::Shl)
2654 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002655 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002656 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002657
Zhou Sheng843f07672007-04-19 05:39:12 +00002658 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002659 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2660 if (CI->equalsInt(1)) // X * 1 == X
2661 return ReplaceInstUsesWith(I, Op0);
2662 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002663 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002664
Zhou Sheng97b52c22007-03-29 01:57:21 +00002665 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002666 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002667 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002668 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002669 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002670 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002671 if (Op1->isNullValue())
2672 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002673
2674 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2675 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002676 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002677
2678 // As above, vector X*splat(1.0) -> X in all defined cases.
2679 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002680 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2681 if (CI->equalsInt(1))
2682 return ReplaceInstUsesWith(I, Op0);
2683 }
2684 }
Chris Lattnera2881962003-02-18 19:28:33 +00002685 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002686
2687 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2688 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002689 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002690 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002691 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2692 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002693 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002694
2695 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002696
2697 // Try to fold constant mul into select arguments.
2698 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002699 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002700 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002701
2702 if (isa<PHINode>(Op0))
2703 if (Instruction *NV = FoldOpIntoPhi(I))
2704 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002705 }
2706
Dan Gohman186a6362009-08-12 16:04:34 +00002707 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2708 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002709 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002710
Nick Lewycky0c730792008-11-21 07:33:58 +00002711 // (X / Y) * Y = X - (X % Y)
2712 // (X / Y) * -Y = (X % Y) - X
2713 {
2714 Value *Op1 = I.getOperand(1);
2715 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2716 if (!BO ||
2717 (BO->getOpcode() != Instruction::UDiv &&
2718 BO->getOpcode() != Instruction::SDiv)) {
2719 Op1 = Op0;
2720 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2721 }
Dan Gohman186a6362009-08-12 16:04:34 +00002722 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002723 if (BO && BO->hasOneUse() &&
2724 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2725 (BO->getOpcode() == Instruction::UDiv ||
2726 BO->getOpcode() == Instruction::SDiv)) {
2727 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2728
Dan Gohmanfa94b942009-08-12 16:33:09 +00002729 // If the division is exact, X % Y is zero.
2730 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2731 if (SDiv->isExact()) {
2732 if (Op1BO == Op1)
2733 return ReplaceInstUsesWith(I, Op0BO);
2734 else
2735 return BinaryOperator::CreateNeg(Op0BO);
2736 }
2737
Chris Lattner74381062009-08-30 07:44:24 +00002738 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002739 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002740 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002741 else
Chris Lattner74381062009-08-30 07:44:24 +00002742 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002743 Rem->takeName(BO);
2744
2745 if (Op1BO == Op1)
2746 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002747 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002748 }
2749 }
2750
Owen Anderson1d0be152009-08-13 21:58:54 +00002751 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002752 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2753
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002754 // If one of the operands of the multiply is a cast from a boolean value, then
2755 // we know the bool is either zero or one, so this is a 'masking' multiply.
2756 // See if we can simplify things based on how the boolean was originally
2757 // formed.
2758 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002759 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002760 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002761 BoolCast = CI;
2762 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002763 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002764 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002765 BoolCast = CI;
2766 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002767 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002768 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2769 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002770 bool TIS = false;
2771
Reid Spencere4d87aa2006-12-23 06:05:41 +00002772 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002773 // multiply into a shift/and combination.
2774 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002775 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2776 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002777 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002778 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002779 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002780 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2781 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002782
2783 // If the multiply type is not the same as the source type, sign extend
2784 // or truncate to the multiply type.
Chris Lattner2345d1d2009-08-30 20:01:10 +00002785 if (I.getType() != V->getType())
2786 V = Builder->CreateIntCast(V, I.getType(), true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002787
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002788 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002789 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002790 }
2791 }
2792 }
2793
Chris Lattner7e708292002-06-25 16:13:24 +00002794 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002795}
2796
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002797Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2798 bool Changed = SimplifyCommutative(I);
2799 Value *Op0 = I.getOperand(0);
2800
2801 // Simplify mul instructions with a constant RHS...
2802 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2803 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2804 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2805 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2806 if (Op1F->isExactlyValue(1.0))
2807 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2808 } else if (isa<VectorType>(Op1->getType())) {
2809 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2810 // As above, vector X*splat(1.0) -> X in all defined cases.
2811 if (Constant *Splat = Op1V->getSplatValue()) {
2812 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2813 if (F->isExactlyValue(1.0))
2814 return ReplaceInstUsesWith(I, Op0);
2815 }
2816 }
2817 }
2818
2819 // Try to fold constant mul into select arguments.
2820 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2821 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2822 return R;
2823
2824 if (isa<PHINode>(Op0))
2825 if (Instruction *NV = FoldOpIntoPhi(I))
2826 return NV;
2827 }
2828
Dan Gohman186a6362009-08-12 16:04:34 +00002829 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2830 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002831 return BinaryOperator::CreateFMul(Op0v, Op1v);
2832
2833 return Changed ? &I : 0;
2834}
2835
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002836/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2837/// instruction.
2838bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2839 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2840
2841 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2842 int NonNullOperand = -1;
2843 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2844 if (ST->isNullValue())
2845 NonNullOperand = 2;
2846 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2847 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2848 if (ST->isNullValue())
2849 NonNullOperand = 1;
2850
2851 if (NonNullOperand == -1)
2852 return false;
2853
2854 Value *SelectCond = SI->getOperand(0);
2855
2856 // Change the div/rem to use 'Y' instead of the select.
2857 I.setOperand(1, SI->getOperand(NonNullOperand));
2858
2859 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2860 // problem. However, the select, or the condition of the select may have
2861 // multiple uses. Based on our knowledge that the operand must be non-zero,
2862 // propagate the known value for the select into other uses of it, and
2863 // propagate a known value of the condition into its other users.
2864
2865 // If the select and condition only have a single use, don't bother with this,
2866 // early exit.
2867 if (SI->use_empty() && SelectCond->hasOneUse())
2868 return true;
2869
2870 // Scan the current block backward, looking for other uses of SI.
2871 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2872
2873 while (BBI != BBFront) {
2874 --BBI;
2875 // If we found a call to a function, we can't assume it will return, so
2876 // information from below it cannot be propagated above it.
2877 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2878 break;
2879
2880 // Replace uses of the select or its condition with the known values.
2881 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2882 I != E; ++I) {
2883 if (*I == SI) {
2884 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002885 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002886 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002887 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2888 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002889 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002890 }
2891 }
2892
2893 // If we past the instruction, quit looking for it.
2894 if (&*BBI == SI)
2895 SI = 0;
2896 if (&*BBI == SelectCond)
2897 SelectCond = 0;
2898
2899 // If we ran out of things to eliminate, break out of the loop.
2900 if (SelectCond == 0 && SI == 0)
2901 break;
2902
2903 }
2904 return true;
2905}
2906
2907
Reid Spencer1628cec2006-10-26 06:15:43 +00002908/// This function implements the transforms on div instructions that work
2909/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2910/// used by the visitors to those instructions.
2911/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002912Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002913 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002914
Chris Lattner50b2ca42008-02-19 06:12:18 +00002915 // undef / X -> 0 for integer.
2916 // undef / X -> undef for FP (the undef could be a snan).
2917 if (isa<UndefValue>(Op0)) {
2918 if (Op0->getType()->isFPOrFPVector())
2919 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002920 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002921 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002922
2923 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002924 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002925 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002926
Reid Spencer1628cec2006-10-26 06:15:43 +00002927 return 0;
2928}
Misha Brukmanfd939082005-04-21 23:48:37 +00002929
Reid Spencer1628cec2006-10-26 06:15:43 +00002930/// This function implements the transforms common to both integer division
2931/// instructions (udiv and sdiv). It is called by the visitors to those integer
2932/// division instructions.
2933/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002934Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002935 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2936
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002937 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002938 if (Op0 == Op1) {
2939 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002940 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002941 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002942 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002943 }
2944
Owen Andersoneed707b2009-07-24 23:12:02 +00002945 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002946 return ReplaceInstUsesWith(I, CI);
2947 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002948
Reid Spencer1628cec2006-10-26 06:15:43 +00002949 if (Instruction *Common = commonDivTransforms(I))
2950 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002951
2952 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2953 // This does not apply for fdiv.
2954 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2955 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002956
2957 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2958 // div X, 1 == X
2959 if (RHS->equalsInt(1))
2960 return ReplaceInstUsesWith(I, Op0);
2961
2962 // (X / C1) / C2 -> X / (C1*C2)
2963 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2964 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2965 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002966 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002967 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002969 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002970 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002971 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002972 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002973
Reid Spencerbca0e382007-03-23 20:05:17 +00002974 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002975 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2976 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2977 return R;
2978 if (isa<PHINode>(Op0))
2979 if (Instruction *NV = FoldOpIntoPhi(I))
2980 return NV;
2981 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002982 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002983
Chris Lattnera2881962003-02-18 19:28:33 +00002984 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002985 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002986 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002987 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002988
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002989 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002990 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002991 return ReplaceInstUsesWith(I, Op0);
2992
Nick Lewycky895f0852008-11-27 20:21:08 +00002993 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2994 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2995 // div X, 1 == X
2996 if (X->isOne())
2997 return ReplaceInstUsesWith(I, Op0);
2998 }
2999
Reid Spencer1628cec2006-10-26 06:15:43 +00003000 return 0;
3001}
3002
3003Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3004 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3005
3006 // Handle the integer div common cases
3007 if (Instruction *Common = commonIDivTransforms(I))
3008 return Common;
3009
Reid Spencer1628cec2006-10-26 06:15:43 +00003010 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003011 // X udiv C^2 -> X >> C
3012 // Check to see if this is an unsigned division with an exact power of 2,
3013 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003014 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003015 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003016 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003017
3018 // X udiv C, where C >= signbit
3019 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003020 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003021 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003022 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003023 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003024 }
3025
3026 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003027 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003028 if (RHSI->getOpcode() == Instruction::Shl &&
3029 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003030 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003031 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003032 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003033 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003034 if (uint32_t C2 = C1.logBase2())
3035 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003036 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003037 }
3038 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003039 }
3040
Reid Spencer1628cec2006-10-26 06:15:43 +00003041 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3042 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003044 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003045 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003046 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003048 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003049 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003050 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003051 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003052 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003053
3054 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003055 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003056 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003057
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003058 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003059 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003061 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003062 return 0;
3063}
3064
Reid Spencer1628cec2006-10-26 06:15:43 +00003065Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3067
3068 // Handle the integer div common cases
3069 if (Instruction *Common = commonIDivTransforms(I))
3070 return Common;
3071
3072 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3073 // sdiv X, -1 == -X
3074 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003075 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003076
Dan Gohmanfa94b942009-08-12 16:33:09 +00003077 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003078 if (cast<SDivOperator>(&I)->isExact() &&
3079 RHS->getValue().isNonNegative() &&
3080 RHS->getValue().isPowerOf2()) {
3081 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3082 RHS->getValue().exactLogBase2());
3083 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3084 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003085
3086 // -X/C --> X/-C provided the negation doesn't overflow.
3087 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3088 if (isa<Constant>(Sub->getOperand(0)) &&
3089 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003090 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003091 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3092 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003093 }
3094
3095 // If the sign bits of both operands are zero (i.e. we can prove they are
3096 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003097 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003098 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003099 if (MaskedValueIsZero(Op0, Mask)) {
3100 if (MaskedValueIsZero(Op1, Mask)) {
3101 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3102 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3103 }
3104 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003105 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003106 ShiftedInt->getValue().isPowerOf2()) {
3107 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3108 // Safe because the only negative value (1 << Y) can take on is
3109 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3110 // the sign bit set.
3111 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3112 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003113 }
Eli Friedman8be17392009-07-18 09:53:21 +00003114 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003115
3116 return 0;
3117}
3118
3119Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3120 return commonDivTransforms(I);
3121}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003122
Reid Spencer0a783f72006-11-02 01:53:59 +00003123/// This function implements the transforms on rem instructions that work
3124/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3125/// is used by the visitors to those instructions.
3126/// @brief Transforms common to all three rem instructions
3127Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003128 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003129
Chris Lattner50b2ca42008-02-19 06:12:18 +00003130 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3131 if (I.getType()->isFPOrFPVector())
3132 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003134 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003135 if (isa<UndefValue>(Op1))
3136 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003137
3138 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003139 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3140 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003141
Reid Spencer0a783f72006-11-02 01:53:59 +00003142 return 0;
3143}
3144
3145/// This function implements the transforms common to both integer remainder
3146/// instructions (urem and srem). It is called by the visitors to those integer
3147/// remainder instructions.
3148/// @brief Common integer remainder transforms
3149Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3150 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3151
3152 if (Instruction *common = commonRemTransforms(I))
3153 return common;
3154
Dale Johannesened6af242009-01-21 00:35:19 +00003155 // 0 % X == 0 for integer, we don't need to preserve faults!
3156 if (Constant *LHS = dyn_cast<Constant>(Op0))
3157 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003158 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003159
Chris Lattner857e8cd2004-12-12 21:48:58 +00003160 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003161 // X % 0 == undef, we don't need to preserve faults!
3162 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003163 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003164
Chris Lattnera2881962003-02-18 19:28:33 +00003165 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003166 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003167
Chris Lattner97943922006-02-28 05:49:21 +00003168 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3169 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3170 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3171 return R;
3172 } else if (isa<PHINode>(Op0I)) {
3173 if (Instruction *NV = FoldOpIntoPhi(I))
3174 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003175 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003176
3177 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003178 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003179 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003180 }
Chris Lattnera2881962003-02-18 19:28:33 +00003181 }
3182
Reid Spencer0a783f72006-11-02 01:53:59 +00003183 return 0;
3184}
3185
3186Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3187 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3188
3189 if (Instruction *common = commonIRemTransforms(I))
3190 return common;
3191
3192 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3193 // X urem C^2 -> X and C
3194 // Check to see if this is an unsigned remainder with an exact power of 2,
3195 // if so, convert to a bitwise and.
3196 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003197 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003198 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 }
3200
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003201 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003202 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3203 if (RHSI->getOpcode() == Instruction::Shl &&
3204 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003205 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003206 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003207 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003208 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003209 }
3210 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003211 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003212
Reid Spencer0a783f72006-11-02 01:53:59 +00003213 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3214 // where C1&C2 are powers of two.
3215 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3216 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3217 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3218 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003219 if ((STO->getValue().isPowerOf2()) &&
3220 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003221 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3222 SI->getName()+".t");
3223 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3224 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003225 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003226 }
3227 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003228 }
3229
Chris Lattner3f5b8772002-05-06 16:14:14 +00003230 return 0;
3231}
3232
Reid Spencer0a783f72006-11-02 01:53:59 +00003233Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3235
Dan Gohmancff55092007-11-05 23:16:33 +00003236 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003237 if (Instruction *Common = commonIRemTransforms(I))
3238 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003239
Dan Gohman186a6362009-08-12 16:04:34 +00003240 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003241 if (!isa<Constant>(RHSNeg) ||
3242 (isa<ConstantInt>(RHSNeg) &&
3243 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003245 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003246 I.setOperand(1, RHSNeg);
3247 return &I;
3248 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003249
Dan Gohmancff55092007-11-05 23:16:33 +00003250 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003252 if (I.getType()->isInteger()) {
3253 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3254 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3255 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003256 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003257 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003258 }
3259
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003260 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003261 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3262 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003263
Nick Lewycky9dce8732008-12-20 16:48:00 +00003264 bool hasNegative = false;
3265 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3267 if (RHS->getValue().isNegative())
3268 hasNegative = true;
3269
3270 if (hasNegative) {
3271 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003272 for (unsigned i = 0; i != VWidth; ++i) {
3273 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3274 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003275 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003276 else
3277 Elts[i] = RHS;
3278 }
3279 }
3280
Owen Andersonaf7ec972009-07-28 21:19:26 +00003281 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003282 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003283 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003284 I.setOperand(1, NewRHSV);
3285 return &I;
3286 }
3287 }
3288 }
3289
Reid Spencer0a783f72006-11-02 01:53:59 +00003290 return 0;
3291}
3292
3293Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003294 return commonRemTransforms(I);
3295}
3296
Chris Lattner457dd822004-06-09 07:59:58 +00003297// isOneBitSet - Return true if there is exactly one bit set in the specified
3298// constant.
3299static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003300 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003301}
3302
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003303// isHighOnes - Return true if the constant is of the form 1+0+.
3304// This is the same as lowones(~X).
3305static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003306 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003307}
3308
Reid Spencere4d87aa2006-12-23 06:05:41 +00003309/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003310/// are carefully arranged to allow folding of expressions such as:
3311///
3312/// (A < B) | (A > B) --> (A != B)
3313///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003314/// Note that this is only valid if the first and second predicates have the
3315/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003316///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003317/// Three bits are used to represent the condition, as follows:
3318/// 0 A > B
3319/// 1 A == B
3320/// 2 A < B
3321///
3322/// <=> Value Definition
3323/// 000 0 Always false
3324/// 001 1 A > B
3325/// 010 2 A == B
3326/// 011 3 A >= B
3327/// 100 4 A < B
3328/// 101 5 A != B
3329/// 110 6 A <= B
3330/// 111 7 Always true
3331///
3332static unsigned getICmpCode(const ICmpInst *ICI) {
3333 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003334 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003335 case ICmpInst::ICMP_UGT: return 1; // 001
3336 case ICmpInst::ICMP_SGT: return 1; // 001
3337 case ICmpInst::ICMP_EQ: return 2; // 010
3338 case ICmpInst::ICMP_UGE: return 3; // 011
3339 case ICmpInst::ICMP_SGE: return 3; // 011
3340 case ICmpInst::ICMP_ULT: return 4; // 100
3341 case ICmpInst::ICMP_SLT: return 4; // 100
3342 case ICmpInst::ICMP_NE: return 5; // 101
3343 case ICmpInst::ICMP_ULE: return 6; // 110
3344 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003345 // True -> 7
3346 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003347 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003348 return 0;
3349 }
3350}
3351
Evan Cheng8db90722008-10-14 17:15:11 +00003352/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3353/// predicate into a three bit mask. It also returns whether it is an ordered
3354/// predicate by reference.
3355static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3356 isOrdered = false;
3357 switch (CC) {
3358 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3359 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003360 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3361 case FCmpInst::FCMP_UGT: return 1; // 001
3362 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3363 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003364 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3365 case FCmpInst::FCMP_UGE: return 3; // 011
3366 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3367 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003368 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3369 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003370 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3371 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003372 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003373 default:
3374 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003375 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003376 return 0;
3377 }
3378}
3379
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380/// getICmpValue - This is the complement of getICmpCode, which turns an
3381/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003382/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003383/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003384static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003385 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003387 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003388 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 case 1:
3390 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003391 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003393 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3394 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003395 case 3:
3396 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003397 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003398 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003399 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 case 4:
3401 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003402 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003404 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3405 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003406 case 6:
3407 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003408 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003409 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003410 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003411 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003412 }
3413}
3414
Evan Cheng8db90722008-10-14 17:15:11 +00003415/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3416/// opcode and two operands into either a FCmp instruction. isordered is passed
3417/// in to determine which kind of predicate to use in the new fcmp instruction.
3418static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003419 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003420 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003421 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003422 case 0:
3423 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003426 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003427 case 1:
3428 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003431 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003432 case 2:
3433 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003435 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003436 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003437 case 3:
3438 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003440 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003441 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003442 case 4:
3443 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003445 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003446 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003447 case 5:
3448 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003450 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003451 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003452 case 6:
3453 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003454 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003455 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003456 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003457 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003458 }
3459}
3460
Chris Lattnerb9553d62008-11-16 04:55:20 +00003461/// PredicatesFoldable - Return true if both predicates match sign or if at
3462/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003463static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3464 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003465 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3466 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467}
3468
3469namespace {
3470// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3471struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003472 InstCombiner &IC;
3473 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003474 ICmpInst::Predicate pred;
3475 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3476 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3477 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003478 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3480 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003481 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3482 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 return false;
3484 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003485 Instruction *apply(Instruction &Log) const {
3486 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3487 if (ICI->getOperand(0) != LHS) {
3488 assert(ICI->getOperand(1) == LHS);
3489 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003490 }
3491
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003492 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003493 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003494 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 unsigned Code;
3496 switch (Log.getOpcode()) {
3497 case Instruction::And: Code = LHSCode & RHSCode; break;
3498 case Instruction::Or: Code = LHSCode | RHSCode; break;
3499 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003500 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 }
3502
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003503 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3504 ICmpInst::isSignedPredicate(ICI->getPredicate());
3505
Owen Andersond672ecb2009-07-03 00:17:18 +00003506 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003507 if (Instruction *I = dyn_cast<Instruction>(RV))
3508 return I;
3509 // Otherwise, it's a constant boolean value...
3510 return IC.ReplaceInstUsesWith(Log, RV);
3511 }
3512};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003513} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003514
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3516// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003517// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003518Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003519 ConstantInt *OpRHS,
3520 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 BinaryOperator &TheAnd) {
3522 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003523 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003524 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003525 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003526
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 switch (Op->getOpcode()) {
3528 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003529 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003530 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003531 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003532 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003533 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534 }
3535 break;
3536 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003537 if (Together == AndRHS) // (X | C) & C --> C
3538 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003539
Chris Lattner6e7ba452005-01-01 16:22:27 +00003540 if (Op->hasOneUse() && Together != OpRHS) {
3541 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003542 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003543 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003544 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003545 }
3546 break;
3547 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003548 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Adding a one to a single bit bit-field should be turned into an XOR
3550 // of the bit. First thing to check is to see if this AND is with a
3551 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003552 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003553
3554 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003555 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003556 // Ok, at this point, we know that we are masking the result of the
3557 // ADD down to exactly one bit. If the constant we are adding has
3558 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003559 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003560
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 // Check to see if any bits below the one bit set in AndRHSV are set.
3562 if ((AddRHS & (AndRHSV-1)) == 0) {
3563 // If not, the only thing that can effect the output of the AND is
3564 // the bit specified by AndRHSV. If that bit is set, the effect of
3565 // the XOR is to toggle the bit. If it is clear, then the ADD has
3566 // no effect.
3567 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3568 TheAnd.setOperand(0, X);
3569 return &TheAnd;
3570 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003571 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003572 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003573 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003574 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003575 }
3576 }
3577 }
3578 }
3579 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003580
3581 case Instruction::Shl: {
3582 // We know that the AND will not produce any of the bits shifted in, so if
3583 // the anded constant includes them, clear them now!
3584 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003585 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003586 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003587 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003588 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003589
Zhou Sheng290bec52007-03-29 08:15:12 +00003590 if (CI->getValue() == ShlMask) {
3591 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003592 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3593 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003594 TheAnd.setOperand(1, CI);
3595 return &TheAnd;
3596 }
3597 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003598 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003599 case Instruction::LShr:
3600 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003601 // We know that the AND will not produce any of the bits shifted in, so if
3602 // the anded constant includes them, clear them now! This only applies to
3603 // unsigned shifts, because a signed shr may bring in set bits!
3604 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003605 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003606 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003607 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003608 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003609
Zhou Sheng290bec52007-03-29 08:15:12 +00003610 if (CI->getValue() == ShrMask) {
3611 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003612 return ReplaceInstUsesWith(TheAnd, Op);
3613 } else if (CI != AndRHS) {
3614 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3615 return &TheAnd;
3616 }
3617 break;
3618 }
3619 case Instruction::AShr:
3620 // Signed shr.
3621 // See if this is shifting in some sign extension, then masking it out
3622 // with an and.
3623 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003624 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003625 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003626 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003627 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003628 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003629 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003630 // Make the argument unsigned.
3631 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003632 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003633 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003634 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003635 }
3636 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003637 }
3638 return 0;
3639}
3640
Chris Lattner8b170942002-08-09 23:47:40 +00003641
Chris Lattnera96879a2004-09-29 17:40:11 +00003642/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3643/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3645/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003646/// insert new instructions.
3647Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 bool isSigned, bool Inside,
3649 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003650 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003651 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003652 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003653
Chris Lattnera96879a2004-09-29 17:40:11 +00003654 if (Inside) {
3655 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003656 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003657
Reid Spencere4d87aa2006-12-23 06:05:41 +00003658 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003659 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003660 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003662 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003663 }
3664
3665 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003666 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003667 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003668 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003669 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003670 }
3671
3672 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003673 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003674
Reid Spencere4e40032007-03-21 23:19:50 +00003675 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003676 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003677 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003678 ICmpInst::Predicate pred = (isSigned ?
3679 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003680 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003681 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003682
Reid Spencere4e40032007-03-21 23:19:50 +00003683 // Emit V-Lo >u Hi-1-Lo
3684 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003685 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003686 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003687 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003688 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003689}
3690
Chris Lattner7203e152005-09-18 07:22:02 +00003691// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3692// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3693// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3694// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003695static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003696 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003697 uint32_t BitWidth = Val->getType()->getBitWidth();
3698 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003699
3700 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003701 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003702 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003703 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003704 return true;
3705}
3706
Chris Lattner7203e152005-09-18 07:22:02 +00003707/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3708/// where isSub determines whether the operator is a sub. If we can fold one of
3709/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003710///
3711/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3712/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3713/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3714///
3715/// return (A +/- B).
3716///
3717Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003718 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003719 Instruction &I) {
3720 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3721 if (!LHSI || LHSI->getNumOperands() != 2 ||
3722 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3723
3724 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3725
3726 switch (LHSI->getOpcode()) {
3727 default: return 0;
3728 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003729 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003730 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003731 if ((Mask->getValue().countLeadingZeros() +
3732 Mask->getValue().countPopulation()) ==
3733 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003734 break;
3735
3736 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3737 // part, we don't need any explicit masks to take them out of A. If that
3738 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003739 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003740 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003741 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003742 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003743 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003744 break;
3745 }
3746 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747 return 0;
3748 case Instruction::Or:
3749 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003750 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003751 if ((Mask->getValue().countLeadingZeros() +
3752 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003753 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754 break;
3755 return 0;
3756 }
3757
Chris Lattnerc8e77562005-09-18 04:24:45 +00003758 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003759 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3760 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003761}
3762
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003763/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3764Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3765 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003766 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003767 ConstantInt *LHSCst, *RHSCst;
3768 ICmpInst::Predicate LHSCC, RHSCC;
3769
Chris Lattnerea065fb2008-11-16 05:10:52 +00003770 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003771 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003772 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003773 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003774 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003775 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003776
3777 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3778 // where C is a power of 2
3779 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3780 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003781 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003782 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003783 }
3784
3785 // From here on, we only handle:
3786 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3787 if (Val != Val2) return 0;
3788
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003789 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3790 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3791 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3792 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3793 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3794 return 0;
3795
3796 // We can't fold (ugt x, C) & (sgt x, C2).
3797 if (!PredicatesFoldable(LHSCC, RHSCC))
3798 return 0;
3799
3800 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003801 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003802 if (ICmpInst::isSignedPredicate(LHSCC) ||
3803 (ICmpInst::isEquality(LHSCC) &&
3804 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003805 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003806 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003807 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3808
3809 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003810 std::swap(LHS, RHS);
3811 std::swap(LHSCst, RHSCst);
3812 std::swap(LHSCC, RHSCC);
3813 }
3814
3815 // At this point, we know we have have two icmp instructions
3816 // comparing a value against two constants and and'ing the result
3817 // together. Because of the above check, we know that we only have
3818 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3819 // (from the FoldICmpLogical check above), that the two constants
3820 // are not equal and that the larger constant is on the RHS
3821 assert(LHSCst != RHSCst && "Compares not folded above?");
3822
3823 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003824 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 case ICmpInst::ICMP_EQ:
3826 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003827 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003828 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3829 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3830 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003831 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3833 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3834 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3835 return ReplaceInstUsesWith(I, LHS);
3836 }
3837 case ICmpInst::ICMP_NE:
3838 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003839 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003841 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003842 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003843 break; // (X != 13 & X u< 15) -> no change
3844 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003845 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003846 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003847 break; // (X != 13 & X s< 15) -> no change
3848 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3849 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3850 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3851 return ReplaceInstUsesWith(I, RHS);
3852 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003853 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003854 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003855 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003856 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003857 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 }
3859 break; // (X != 13 & X != 15) -> no change
3860 }
3861 break;
3862 case ICmpInst::ICMP_ULT:
3863 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003864 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003865 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3866 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003867 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003868 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3869 break;
3870 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3871 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3872 return ReplaceInstUsesWith(I, LHS);
3873 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3874 break;
3875 }
3876 break;
3877 case ICmpInst::ICMP_SLT:
3878 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003879 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003880 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3881 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003882 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003883 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3884 break;
3885 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3886 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3887 return ReplaceInstUsesWith(I, LHS);
3888 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3889 break;
3890 }
3891 break;
3892 case ICmpInst::ICMP_UGT:
3893 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003894 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003895 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3896 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3897 return ReplaceInstUsesWith(I, RHS);
3898 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3899 break;
3900 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003901 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003902 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003903 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003904 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003905 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003906 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003907 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3908 break;
3909 }
3910 break;
3911 case ICmpInst::ICMP_SGT:
3912 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003913 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003914 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3915 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3916 return ReplaceInstUsesWith(I, RHS);
3917 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3918 break;
3919 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003920 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003921 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003922 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003923 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003924 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003925 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003926 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3927 break;
3928 }
3929 break;
3930 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003931
3932 return 0;
3933}
3934
Chris Lattner42d1be02009-07-23 05:14:02 +00003935Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3936 FCmpInst *RHS) {
3937
3938 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3939 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3940 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3941 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3942 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3943 // If either of the constants are nans, then the whole thing returns
3944 // false.
3945 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003946 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003947 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003948 LHS->getOperand(0), RHS->getOperand(0));
3949 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003950
3951 // Handle vector zeros. This occurs because the canonical form of
3952 // "fcmp ord x,x" is "fcmp ord x, 0".
3953 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3954 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003955 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003956 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003957 return 0;
3958 }
3959
3960 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3961 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3962 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3963
3964
3965 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3966 // Swap RHS operands to match LHS.
3967 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3968 std::swap(Op1LHS, Op1RHS);
3969 }
3970
3971 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3972 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3973 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003974 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003975
3976 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003977 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003978 if (Op0CC == FCmpInst::FCMP_TRUE)
3979 return ReplaceInstUsesWith(I, RHS);
3980 if (Op1CC == FCmpInst::FCMP_TRUE)
3981 return ReplaceInstUsesWith(I, LHS);
3982
3983 bool Op0Ordered;
3984 bool Op1Ordered;
3985 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3986 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3987 if (Op1Pred == 0) {
3988 std::swap(LHS, RHS);
3989 std::swap(Op0Pred, Op1Pred);
3990 std::swap(Op0Ordered, Op1Ordered);
3991 }
3992 if (Op0Pred == 0) {
3993 // uno && ueq -> uno && (uno || eq) -> ueq
3994 // ord && olt -> ord && (ord && lt) -> olt
3995 if (Op0Ordered == Op1Ordered)
3996 return ReplaceInstUsesWith(I, RHS);
3997
3998 // uno && oeq -> uno && (ord && eq) -> false
3999 // uno && ord -> false
4000 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004001 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004002 // ord && ueq -> ord && (uno || eq) -> oeq
4003 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4004 Op0LHS, Op0RHS, Context));
4005 }
4006 }
4007
4008 return 0;
4009}
4010
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004011
Chris Lattner7e708292002-06-25 16:13:24 +00004012Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004013 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004014 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004015
Chris Lattnere87597f2004-10-16 18:11:37 +00004016 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004018
Chris Lattner6e7ba452005-01-01 16:22:27 +00004019 // and X, X = X
4020 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004021 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004022
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004023 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004024 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004025 if (SimplifyDemandedInstructionBits(I))
4026 return &I;
4027 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004028 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004029 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004030 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004031 } else if (isa<ConstantAggregateZero>(Op1)) {
4032 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004033 }
4034 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004035
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004036 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004037 const APInt& AndRHSMask = AndRHS->getValue();
4038 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004039
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004040 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004041 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004042 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004043 Value *Op0LHS = Op0I->getOperand(0);
4044 Value *Op0RHS = Op0I->getOperand(1);
4045 switch (Op0I->getOpcode()) {
4046 case Instruction::Xor:
4047 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004048 // If the mask is only needed on one incoming arm, push it up.
4049 if (Op0I->hasOneUse()) {
4050 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4051 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004052 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4053 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004054 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004055 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004056 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004057 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004058 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4059 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004060 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4061 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004062 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004063 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4064 }
4065 }
4066
Chris Lattner6e7ba452005-01-01 16:22:27 +00004067 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004068 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004069 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4070 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4071 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4072 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004073 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004074 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004075 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004076 break;
4077
4078 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004079 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4080 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4081 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4082 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004083 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004084
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004085 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4086 // has 1's for all bits that the subtraction with A might affect.
4087 if (Op0I->hasOneUse()) {
4088 uint32_t BitWidth = AndRHSMask.getBitWidth();
4089 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4090 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4091
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004092 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004093 if (!(A && A->isZero()) && // avoid infinite recursion.
4094 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004095 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004096 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4097 }
4098 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004099 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004100
4101 case Instruction::Shl:
4102 case Instruction::LShr:
4103 // (1 << x) & 1 --> zext(x == 0)
4104 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004105 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004106 Value *NewICmp =
4107 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004108 return new ZExtInst(NewICmp, I.getType());
4109 }
4110 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004111 }
4112
Chris Lattner58403262003-07-23 19:25:52 +00004113 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004114 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004115 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004116 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004117 // If this is an integer truncation or change from signed-to-unsigned, and
4118 // if the source is an and/or with immediate, transform it. This
4119 // frequently occurs for bitfield accesses.
4120 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004121 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004122 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004123 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004124 if (CastOp->getOpcode() == Instruction::And) {
4125 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004126 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4127 // This will fold the two constants together, which may allow
4128 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004129 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004130 CastOp->getOperand(0), I.getType(),
4131 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004132 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004133 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004134 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 } else if (CastOp->getOpcode() == Instruction::Or) {
4137 // Change: and (cast (or X, C1) to T), C2
4138 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004139 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004140 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004141 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004142 return ReplaceInstUsesWith(I, AndRHS);
4143 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004144 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004145 }
Chris Lattner06782f82003-07-23 19:36:21 +00004146 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004147
4148 // Try to fold constant and into select arguments.
4149 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004150 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004151 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004152 if (isa<PHINode>(Op0))
4153 if (Instruction *NV = FoldOpIntoPhi(I))
4154 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004155 }
4156
Dan Gohman186a6362009-08-12 16:04:34 +00004157 Value *Op0NotVal = dyn_castNotVal(Op0);
4158 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004159
Chris Lattner5b62aa72004-06-18 06:07:51 +00004160 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004161 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004162
Misha Brukmancb6267b2004-07-30 12:50:08 +00004163 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004164 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004165 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4166 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004167 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004168 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004169
4170 {
Chris Lattner003b6202007-06-15 05:58:24 +00004171 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004172 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004173 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4174 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004175
4176 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004177 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004178 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004179 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004180 }
4181 }
4182
Dan Gohman4ae51262009-08-12 16:23:25 +00004183 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004184 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4185 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004186
4187 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004188 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004189 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004190 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004191 }
4192 }
Chris Lattner64daab52006-04-01 08:03:55 +00004193
4194 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004195 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004196 if (A == Op1) { // (A^B)&A -> A&(A^B)
4197 I.swapOperands(); // Simplify below
4198 std::swap(Op0, Op1);
4199 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4200 cast<BinaryOperator>(Op0)->swapOperands();
4201 I.swapOperands(); // Simplify below
4202 std::swap(Op0, Op1);
4203 }
4204 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004205
Chris Lattner64daab52006-04-01 08:03:55 +00004206 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004207 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004208 if (B == Op0) { // B&(A^B) -> B&(B^A)
4209 cast<BinaryOperator>(Op1)->swapOperands();
4210 std::swap(A, B);
4211 }
Chris Lattner74381062009-08-30 07:44:24 +00004212 if (A == Op0) // A&(A^B) -> A & ~B
4213 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004214 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004215
4216 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004217 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4218 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004219 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004220 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4221 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004222 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004223 }
4224
Reid Spencere4d87aa2006-12-23 06:05:41 +00004225 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4226 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004227 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004228 return R;
4229
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004230 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4231 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4232 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004233 }
4234
Chris Lattner6fc205f2006-05-05 06:39:07 +00004235 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004236 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4237 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4238 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4239 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004240 if (SrcTy == Op1C->getOperand(0)->getType() &&
4241 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004242 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004243 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4244 I.getType(), TD) &&
4245 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4246 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004247 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4248 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004249 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004250 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004251 }
Chris Lattnere511b742006-11-14 07:46:50 +00004252
4253 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004254 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4255 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4256 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004257 SI0->getOperand(1) == SI1->getOperand(1) &&
4258 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004259 Value *NewOp =
4260 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4261 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004262 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004263 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004264 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004265 }
4266
Evan Cheng8db90722008-10-14 17:15:11 +00004267 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004268 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004269 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4270 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4271 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004272 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004273
Chris Lattner7e708292002-06-25 16:13:24 +00004274 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004275}
4276
Chris Lattner8c34cd22008-10-05 02:13:19 +00004277/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4278/// capable of providing pieces of a bswap. The subexpression provides pieces
4279/// of a bswap if it is proven that each of the non-zero bytes in the output of
4280/// the expression came from the corresponding "byte swapped" byte in some other
4281/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4282/// we know that the expression deposits the low byte of %X into the high byte
4283/// of the bswap result and that all other bytes are zero. This expression is
4284/// accepted, the high byte of ByteValues is set to X to indicate a correct
4285/// match.
4286///
4287/// This function returns true if the match was unsuccessful and false if so.
4288/// On entry to the function the "OverallLeftShift" is a signed integer value
4289/// indicating the number of bytes that the subexpression is later shifted. For
4290/// example, if the expression is later right shifted by 16 bits, the
4291/// OverallLeftShift value would be -2 on entry. This is used to specify which
4292/// byte of ByteValues is actually being set.
4293///
4294/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4295/// byte is masked to zero by a user. For example, in (X & 255), X will be
4296/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4297/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4298/// always in the local (OverallLeftShift) coordinate space.
4299///
4300static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4301 SmallVector<Value*, 8> &ByteValues) {
4302 if (Instruction *I = dyn_cast<Instruction>(V)) {
4303 // If this is an or instruction, it may be an inner node of the bswap.
4304 if (I->getOpcode() == Instruction::Or) {
4305 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4306 ByteValues) ||
4307 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4308 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004309 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004310
4311 // If this is a logical shift by a constant multiple of 8, recurse with
4312 // OverallLeftShift and ByteMask adjusted.
4313 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4314 unsigned ShAmt =
4315 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4316 // Ensure the shift amount is defined and of a byte value.
4317 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4318 return true;
4319
4320 unsigned ByteShift = ShAmt >> 3;
4321 if (I->getOpcode() == Instruction::Shl) {
4322 // X << 2 -> collect(X, +2)
4323 OverallLeftShift += ByteShift;
4324 ByteMask >>= ByteShift;
4325 } else {
4326 // X >>u 2 -> collect(X, -2)
4327 OverallLeftShift -= ByteShift;
4328 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004329 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004330 }
4331
4332 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4333 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4334
4335 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336 ByteValues);
4337 }
4338
4339 // If this is a logical 'and' with a mask that clears bytes, clear the
4340 // corresponding bytes in ByteMask.
4341 if (I->getOpcode() == Instruction::And &&
4342 isa<ConstantInt>(I->getOperand(1))) {
4343 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4344 unsigned NumBytes = ByteValues.size();
4345 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4346 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4347
4348 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4349 // If this byte is masked out by a later operation, we don't care what
4350 // the and mask is.
4351 if ((ByteMask & (1 << i)) == 0)
4352 continue;
4353
4354 // If the AndMask is all zeros for this byte, clear the bit.
4355 APInt MaskB = AndMask & Byte;
4356 if (MaskB == 0) {
4357 ByteMask &= ~(1U << i);
4358 continue;
4359 }
4360
4361 // If the AndMask is not all ones for this byte, it's not a bytezap.
4362 if (MaskB != Byte)
4363 return true;
4364
4365 // Otherwise, this byte is kept.
4366 }
4367
4368 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4369 ByteValues);
4370 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004371 }
4372
Chris Lattner8c34cd22008-10-05 02:13:19 +00004373 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4374 // the input value to the bswap. Some observations: 1) if more than one byte
4375 // is demanded from this input, then it could not be successfully assembled
4376 // into a byteswap. At least one of the two bytes would not be aligned with
4377 // their ultimate destination.
4378 if (!isPowerOf2_32(ByteMask)) return true;
4379 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004380
Chris Lattner8c34cd22008-10-05 02:13:19 +00004381 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4382 // is demanded, it needs to go into byte 0 of the result. This means that the
4383 // byte needs to be shifted until it lands in the right byte bucket. The
4384 // shift amount depends on the position: if the byte is coming from the high
4385 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4386 // low part, it must be shifted left.
4387 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4388 if (InputByteNo < ByteValues.size()/2) {
4389 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4390 return true;
4391 } else {
4392 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4393 return true;
4394 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004395
4396 // If the destination byte value is already defined, the values are or'd
4397 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004398 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004399 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004400 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004401 return false;
4402}
4403
4404/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4405/// If so, insert the new bswap intrinsic and return it.
4406Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004407 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004408 if (!ITy || ITy->getBitWidth() % 16 ||
4409 // ByteMask only allows up to 32-byte values.
4410 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004411 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004412
4413 /// ByteValues - For each byte of the result, we keep track of which value
4414 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004415 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004416 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417
4418 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004419 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4420 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004421 return 0;
4422
4423 // Check to see if all of the bytes come from the same value.
4424 Value *V = ByteValues[0];
4425 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4426
4427 // Check to make sure that all of the bytes come from the same value.
4428 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4429 if (ByteValues[i] != V)
4430 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004431 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004432 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004433 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004434 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004435}
4436
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004437/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4438/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4439/// we can simplify this expression to "cond ? C : D or B".
4440static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004441 Value *C, Value *D,
4442 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004443 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004444 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004445 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004446 return 0;
4447
Chris Lattnera6a474d2008-11-16 04:26:55 +00004448 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004449 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004450 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004451 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004452 return SelectInst::Create(Cond, C, B);
4453 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004454 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004455 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004456 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004457 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004458 return 0;
4459}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004460
Chris Lattner69d4ced2008-11-16 05:20:07 +00004461/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4462Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4463 ICmpInst *LHS, ICmpInst *RHS) {
4464 Value *Val, *Val2;
4465 ConstantInt *LHSCst, *RHSCst;
4466 ICmpInst::Predicate LHSCC, RHSCC;
4467
4468 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004469 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004470 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004471 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004472 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004473 return 0;
4474
4475 // From here on, we only handle:
4476 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4477 if (Val != Val2) return 0;
4478
4479 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4480 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4481 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4482 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4483 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4484 return 0;
4485
4486 // We can't fold (ugt x, C) | (sgt x, C2).
4487 if (!PredicatesFoldable(LHSCC, RHSCC))
4488 return 0;
4489
4490 // Ensure that the larger constant is on the RHS.
4491 bool ShouldSwap;
4492 if (ICmpInst::isSignedPredicate(LHSCC) ||
4493 (ICmpInst::isEquality(LHSCC) &&
4494 ICmpInst::isSignedPredicate(RHSCC)))
4495 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4496 else
4497 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4498
4499 if (ShouldSwap) {
4500 std::swap(LHS, RHS);
4501 std::swap(LHSCst, RHSCst);
4502 std::swap(LHSCC, RHSCC);
4503 }
4504
4505 // At this point, we know we have have two icmp instructions
4506 // comparing a value against two constants and or'ing the result
4507 // together. Because of the above check, we know that we only have
4508 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4509 // FoldICmpLogical check above), that the two constants are not
4510 // equal.
4511 assert(LHSCst != RHSCst && "Compares not folded above?");
4512
4513 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004514 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004515 case ICmpInst::ICMP_EQ:
4516 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004517 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004518 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004519 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004520 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004521 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004522 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004523 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004524 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004525 }
4526 break; // (X == 13 | X == 15) -> no change
4527 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4528 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4529 break;
4530 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4531 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4532 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4533 return ReplaceInstUsesWith(I, RHS);
4534 }
4535 break;
4536 case ICmpInst::ICMP_NE:
4537 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004538 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004539 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4540 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4541 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4542 return ReplaceInstUsesWith(I, LHS);
4543 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4544 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4545 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004546 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004547 }
4548 break;
4549 case ICmpInst::ICMP_ULT:
4550 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004551 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004552 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4553 break;
4554 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4555 // If RHSCst is [us]MAXINT, it is always false. Not handling
4556 // this can cause overflow.
4557 if (RHSCst->isMaxValue(false))
4558 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004559 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004560 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004561 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4562 break;
4563 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4564 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4565 return ReplaceInstUsesWith(I, RHS);
4566 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4567 break;
4568 }
4569 break;
4570 case ICmpInst::ICMP_SLT:
4571 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004572 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004573 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4574 break;
4575 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4576 // If RHSCst is [us]MAXINT, it is always false. Not handling
4577 // this can cause overflow.
4578 if (RHSCst->isMaxValue(true))
4579 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004580 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004581 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004582 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4583 break;
4584 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4585 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4586 return ReplaceInstUsesWith(I, RHS);
4587 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4588 break;
4589 }
4590 break;
4591 case ICmpInst::ICMP_UGT:
4592 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004593 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004594 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4595 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4596 return ReplaceInstUsesWith(I, LHS);
4597 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4598 break;
4599 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4600 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004601 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004602 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4603 break;
4604 }
4605 break;
4606 case ICmpInst::ICMP_SGT:
4607 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004608 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004609 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4610 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4611 return ReplaceInstUsesWith(I, LHS);
4612 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4613 break;
4614 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4615 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004616 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004617 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4618 break;
4619 }
4620 break;
4621 }
4622 return 0;
4623}
4624
Chris Lattner5414cc52009-07-23 05:46:22 +00004625Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4626 FCmpInst *RHS) {
4627 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4628 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4629 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4630 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4631 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4632 // If either of the constants are nans, then the whole thing returns
4633 // true.
4634 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004635 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004636
4637 // Otherwise, no need to compare the two constants, compare the
4638 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004639 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004640 LHS->getOperand(0), RHS->getOperand(0));
4641 }
4642
4643 // Handle vector zeros. This occurs because the canonical form of
4644 // "fcmp uno x,x" is "fcmp uno x, 0".
4645 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4646 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004647 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004648 LHS->getOperand(0), RHS->getOperand(0));
4649
4650 return 0;
4651 }
4652
4653 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4654 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4655 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4656
4657 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4658 // Swap RHS operands to match LHS.
4659 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4660 std::swap(Op1LHS, Op1RHS);
4661 }
4662 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4663 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4664 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004665 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004666 Op0LHS, Op0RHS);
4667 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004668 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004669 if (Op0CC == FCmpInst::FCMP_FALSE)
4670 return ReplaceInstUsesWith(I, RHS);
4671 if (Op1CC == FCmpInst::FCMP_FALSE)
4672 return ReplaceInstUsesWith(I, LHS);
4673 bool Op0Ordered;
4674 bool Op1Ordered;
4675 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4676 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4677 if (Op0Ordered == Op1Ordered) {
4678 // If both are ordered or unordered, return a new fcmp with
4679 // or'ed predicates.
4680 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4681 Op0LHS, Op0RHS, Context);
4682 if (Instruction *I = dyn_cast<Instruction>(RV))
4683 return I;
4684 // Otherwise, it's a constant boolean value...
4685 return ReplaceInstUsesWith(I, RV);
4686 }
4687 }
4688 return 0;
4689}
4690
Bill Wendlinga698a472008-12-01 08:23:25 +00004691/// FoldOrWithConstants - This helper function folds:
4692///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004693/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004694///
4695/// into:
4696///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004697/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004698///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004699/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004700Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004701 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004702 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4703 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004704
Bill Wendling286a0542008-12-02 06:24:20 +00004705 Value *V1 = 0;
4706 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004707 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004708
Bill Wendling29976b92008-12-02 06:18:11 +00004709 APInt Xor = CI1->getValue() ^ CI2->getValue();
4710 if (!Xor.isAllOnesValue()) return 0;
4711
Bill Wendling286a0542008-12-02 06:24:20 +00004712 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004713 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004714 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004715 }
4716
4717 return 0;
4718}
4719
Chris Lattner7e708292002-06-25 16:13:24 +00004720Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004721 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004722 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004723
Chris Lattner42593e62007-03-24 23:56:43 +00004724 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004725 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004726
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004727 // or X, X = X
4728 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004729 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004730
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004731 // See if we can simplify any instructions used by the instruction whose sole
4732 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004733 if (SimplifyDemandedInstructionBits(I))
4734 return &I;
4735 if (isa<VectorType>(I.getType())) {
4736 if (isa<ConstantAggregateZero>(Op1)) {
4737 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4738 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4739 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4740 return ReplaceInstUsesWith(I, I.getOperand(1));
4741 }
Chris Lattner42593e62007-03-24 23:56:43 +00004742 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004743
Chris Lattner3f5b8772002-05-06 16:14:14 +00004744 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004745 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004746 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004747 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004748 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004749 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004750 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004751 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004752 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004753 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004754 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004755
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004756 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004757 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004758 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004759 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004760 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004761 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004762 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004763 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004764
4765 // Try to fold constant and into select arguments.
4766 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004767 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004768 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004769 if (isa<PHINode>(Op0))
4770 if (Instruction *NV = FoldOpIntoPhi(I))
4771 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004772 }
4773
Chris Lattner4f637d42006-01-06 17:59:59 +00004774 Value *A = 0, *B = 0;
4775 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004776
Dan Gohman4ae51262009-08-12 16:23:25 +00004777 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004778 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4779 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004780 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004781 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4782 return ReplaceInstUsesWith(I, Op0);
4783
Chris Lattner6423d4c2006-07-10 20:25:24 +00004784 // (A | B) | C and A | (B | C) -> bswap if possible.
4785 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004786 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4787 match(Op1, m_Or(m_Value(), m_Value())) ||
4788 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4789 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004790 if (Instruction *BSwap = MatchBSwap(I))
4791 return BSwap;
4792 }
4793
Chris Lattner6e4c6492005-05-09 04:58:36 +00004794 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004795 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004796 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004797 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004798 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004799 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004800 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004801 }
4802
4803 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004804 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004805 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004806 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004807 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004808 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004809 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004810 }
4811
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004812 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004813 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004814 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4815 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004816 Value *V1 = 0, *V2 = 0, *V3 = 0;
4817 C1 = dyn_cast<ConstantInt>(C);
4818 C2 = dyn_cast<ConstantInt>(D);
4819 if (C1 && C2) { // (A & C1)|(B & C2)
4820 // If we have: ((V + N) & C1) | (V & C2)
4821 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4822 // replace with V+N.
4823 if (C1->getValue() == ~C2->getValue()) {
4824 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004825 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004826 // Add commutes, try both ways.
4827 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4828 return ReplaceInstUsesWith(I, A);
4829 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4830 return ReplaceInstUsesWith(I, A);
4831 }
4832 // Or commutes, try both ways.
4833 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004834 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004835 // Add commutes, try both ways.
4836 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4837 return ReplaceInstUsesWith(I, B);
4838 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4839 return ReplaceInstUsesWith(I, B);
4840 }
4841 }
Chris Lattner044e5332007-04-08 08:01:49 +00004842 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004843 }
4844
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004845 // Check to see if we have any common things being and'ed. If so, find the
4846 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004847 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4848 if (A == B) // (A & C)|(A & D) == A & (C|D)
4849 V1 = A, V2 = C, V3 = D;
4850 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4851 V1 = A, V2 = B, V3 = C;
4852 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4853 V1 = C, V2 = A, V3 = D;
4854 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4855 V1 = C, V2 = A, V3 = B;
4856
4857 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004858 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004859 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004860 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004861 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004862
Dan Gohman1975d032008-10-30 20:40:10 +00004863 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004864 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004865 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004866 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004867 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004868 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004869 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004870 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004871 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004872
Bill Wendlingb01865c2008-11-30 13:52:49 +00004873 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004874 if ((match(C, m_Not(m_Specific(D))) &&
4875 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004876 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004877 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004878 if ((match(A, m_Not(m_Specific(D))) &&
4879 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004880 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004881 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004882 if ((match(C, m_Not(m_Specific(B))) &&
4883 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004884 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004885 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004886 if ((match(A, m_Not(m_Specific(B))) &&
4887 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004888 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004889 }
Chris Lattnere511b742006-11-14 07:46:50 +00004890
4891 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004892 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4893 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4894 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004895 SI0->getOperand(1) == SI1->getOperand(1) &&
4896 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004897 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4898 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004899 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004900 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004901 }
4902 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004903
Bill Wendlingb3833d12008-12-01 01:07:11 +00004904 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004905 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4906 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004907 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004908 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004909 }
4910 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004911 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4912 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004913 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004914 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004915 }
4916
Dan Gohman4ae51262009-08-12 16:23:25 +00004917 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004918 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004919 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004920 } else {
4921 A = 0;
4922 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004923 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004924 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004925 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004926 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004927
Misha Brukmancb6267b2004-07-30 12:50:08 +00004928 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004929 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004930 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004931 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004932 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004933 }
Chris Lattnera2881962003-02-18 19:28:33 +00004934
Reid Spencere4d87aa2006-12-23 06:05:41 +00004935 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4936 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004937 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004938 return R;
4939
Chris Lattner69d4ced2008-11-16 05:20:07 +00004940 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4941 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4942 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004943 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004944
4945 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004946 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004947 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004948 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004949 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4950 !isa<ICmpInst>(Op1C->getOperand(0))) {
4951 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004952 if (SrcTy == Op1C->getOperand(0)->getType() &&
4953 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004954 // Only do this if the casts both really cause code to be
4955 // generated.
4956 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4957 I.getType(), TD) &&
4958 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4959 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004960 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4961 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004962 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004963 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004964 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004965 }
Chris Lattner99c65742007-10-24 05:38:08 +00004966 }
4967
4968
4969 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4970 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004971 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4972 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4973 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004974 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004975
Chris Lattner7e708292002-06-25 16:13:24 +00004976 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004977}
4978
Dan Gohman844731a2008-05-13 00:00:25 +00004979namespace {
4980
Chris Lattnerc317d392004-02-16 01:20:27 +00004981// XorSelf - Implements: X ^ X --> 0
4982struct XorSelf {
4983 Value *RHS;
4984 XorSelf(Value *rhs) : RHS(rhs) {}
4985 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4986 Instruction *apply(BinaryOperator &Xor) const {
4987 return &Xor;
4988 }
4989};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004990
Dan Gohman844731a2008-05-13 00:00:25 +00004991}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004992
Chris Lattner7e708292002-06-25 16:13:24 +00004993Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004994 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004995 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004996
Evan Chengd34af782008-03-25 20:07:13 +00004997 if (isa<UndefValue>(Op1)) {
4998 if (isa<UndefValue>(Op0))
4999 // Handle undef ^ undef -> 0 special case. This is a common
5000 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005001 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005002 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005003 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005004
Chris Lattnerc317d392004-02-16 01:20:27 +00005005 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005006 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005007 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005008 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005009 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005010
5011 // See if we can simplify any instructions used by the instruction whose sole
5012 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005013 if (SimplifyDemandedInstructionBits(I))
5014 return &I;
5015 if (isa<VectorType>(I.getType()))
5016 if (isa<ConstantAggregateZero>(Op1))
5017 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005018
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005019 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005020 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005021 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5022 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5023 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5024 if (Op0I->getOpcode() == Instruction::And ||
5025 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005026 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5027 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005028 Value *NotY =
5029 Builder->CreateNot(Op0I->getOperand(1),
5030 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005031 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005032 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005033 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005034 }
5035 }
5036 }
5037 }
5038
5039
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005040 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005041 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005042 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005043 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005044 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005045 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005046
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005047 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005048 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005049 FCI->getOperand(0), FCI->getOperand(1));
5050 }
5051
Nick Lewycky517e1f52008-05-31 19:01:33 +00005052 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5053 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5054 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5055 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5056 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005057 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5058 (RHS == ConstantExpr::getCast(Opcode,
5059 ConstantInt::getTrue(*Context),
5060 Op0C->getDestTy()))) {
5061 CI->setPredicate(CI->getInversePredicate());
5062 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005063 }
5064 }
5065 }
5066 }
5067
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005069 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005070 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5071 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005072 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5073 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005074 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005075 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005076 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005077
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005078 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005079 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005080 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005081 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005082 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005083 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005084 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005085 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005086 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005087 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005088 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005089 Constant *C = ConstantInt::get(*Context,
5090 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005091 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005092
Chris Lattner7c4049c2004-01-12 19:35:11 +00005093 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005094 } else if (Op0I->getOpcode() == Instruction::Or) {
5095 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005096 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005097 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005098 // Anything in both C1 and C2 is known to be zero, remove it from
5099 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005100 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5101 NewRHS = ConstantExpr::getAnd(NewRHS,
5102 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005103 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005104 I.setOperand(0, Op0I->getOperand(0));
5105 I.setOperand(1, NewRHS);
5106 return &I;
5107 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005108 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005109 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005110 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005111
5112 // Try to fold constant and into select arguments.
5113 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005115 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005116 if (isa<PHINode>(Op0))
5117 if (Instruction *NV = FoldOpIntoPhi(I))
5118 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005119 }
5120
Dan Gohman186a6362009-08-12 16:04:34 +00005121 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005122 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005123 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005124
Dan Gohman186a6362009-08-12 16:04:34 +00005125 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005126 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005127 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005128
Chris Lattner318bf792007-03-18 22:51:34 +00005129
5130 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5131 if (Op1I) {
5132 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005133 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005134 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005135 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005136 I.swapOperands();
5137 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005138 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005139 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005140 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005141 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005142 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005143 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005144 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005145 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005146 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005147 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005148 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005149 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005150 std::swap(A, B);
5151 }
Chris Lattner318bf792007-03-18 22:51:34 +00005152 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005153 I.swapOperands(); // Simplified below.
5154 std::swap(Op0, Op1);
5155 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005156 }
Chris Lattner318bf792007-03-18 22:51:34 +00005157 }
5158
5159 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5160 if (Op0I) {
5161 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005162 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005163 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005164 if (A == Op1) // (B|A)^B == (A|B)^B
5165 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005166 if (B == Op1) // (A|B)^B == A & ~B
5167 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005168 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005169 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005170 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005171 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005172 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005173 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005174 if (A == Op1) // (A&B)^A -> (B&A)^A
5175 std::swap(A, B);
5176 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005177 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005178 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005179 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005180 }
Chris Lattner318bf792007-03-18 22:51:34 +00005181 }
5182
5183 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5184 if (Op0I && Op1I && Op0I->isShift() &&
5185 Op0I->getOpcode() == Op1I->getOpcode() &&
5186 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5187 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005188 Value *NewOp =
5189 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5190 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005191 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005192 Op1I->getOperand(1));
5193 }
5194
5195 if (Op0I && Op1I) {
5196 Value *A, *B, *C, *D;
5197 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005198 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5199 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005200 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005201 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005202 }
5203 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005204 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5205 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005206 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005208 }
5209
5210 // (A & B)^(C & D)
5211 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005212 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5213 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005214 // (X & Y)^(X & Y) -> (Y^Z) & X
5215 Value *X = 0, *Y = 0, *Z = 0;
5216 if (A == C)
5217 X = A, Y = B, Z = D;
5218 else if (A == D)
5219 X = A, Y = B, Z = C;
5220 else if (B == C)
5221 X = B, Y = A, Z = D;
5222 else if (B == D)
5223 X = B, Y = A, Z = C;
5224
5225 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005226 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005227 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005228 }
5229 }
5230 }
5231
Reid Spencere4d87aa2006-12-23 06:05:41 +00005232 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5233 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005234 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005235 return R;
5236
Chris Lattner6fc205f2006-05-05 06:39:07 +00005237 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005238 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005239 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005240 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5241 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005242 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005243 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005244 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5245 I.getType(), TD) &&
5246 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5247 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005248 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5249 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005250 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005251 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005252 }
Chris Lattner99c65742007-10-24 05:38:08 +00005253 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005254
Chris Lattner7e708292002-06-25 16:13:24 +00005255 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005256}
5257
Owen Andersond672ecb2009-07-03 00:17:18 +00005258static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005259 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005260 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005261}
Chris Lattnera96879a2004-09-29 17:40:11 +00005262
Dan Gohman6de29f82009-06-15 22:12:54 +00005263static bool HasAddOverflow(ConstantInt *Result,
5264 ConstantInt *In1, ConstantInt *In2,
5265 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005266 if (IsSigned)
5267 if (In2->getValue().isNegative())
5268 return Result->getValue().sgt(In1->getValue());
5269 else
5270 return Result->getValue().slt(In1->getValue());
5271 else
5272 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005273}
5274
Dan Gohman6de29f82009-06-15 22:12:54 +00005275/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005276/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005277static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005278 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005279 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005280 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005281
Dan Gohman6de29f82009-06-15 22:12:54 +00005282 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5283 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005284 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005285 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5286 ExtractElement(In1, Idx, Context),
5287 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005288 IsSigned))
5289 return true;
5290 }
5291 return false;
5292 }
5293
5294 return HasAddOverflow(cast<ConstantInt>(Result),
5295 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5296 IsSigned);
5297}
5298
5299static bool HasSubOverflow(ConstantInt *Result,
5300 ConstantInt *In1, ConstantInt *In2,
5301 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005302 if (IsSigned)
5303 if (In2->getValue().isNegative())
5304 return Result->getValue().slt(In1->getValue());
5305 else
5306 return Result->getValue().sgt(In1->getValue());
5307 else
5308 return Result->getValue().ugt(In1->getValue());
5309}
5310
Dan Gohman6de29f82009-06-15 22:12:54 +00005311/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5312/// overflowed for this type.
5313static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005314 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005315 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005316 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005317
5318 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5319 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005320 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005321 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5322 ExtractElement(In1, Idx, Context),
5323 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005324 IsSigned))
5325 return true;
5326 }
5327 return false;
5328 }
5329
5330 return HasSubOverflow(cast<ConstantInt>(Result),
5331 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5332 IsSigned);
5333}
5334
Chris Lattner574da9b2005-01-13 20:14:25 +00005335/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5336/// code necessary to compute the offset from the base pointer (without adding
5337/// in the base pointer). Return the result as a signed integer of intptr size.
5338static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005339 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005340 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005341 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005342 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005343
5344 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005345 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005346 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005347
Gabor Greif177dd3f2008-06-12 21:37:33 +00005348 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5349 ++i, ++GTI) {
5350 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005351 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005352 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5353 if (OpC->isZero()) continue;
5354
5355 // Handle a struct index, which adds its field offset to the pointer.
5356 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5357 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5358
Chris Lattner74381062009-08-30 07:44:24 +00005359 Result = IC.Builder->CreateAdd(Result,
5360 ConstantInt::get(IntPtrTy, Size),
5361 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005362 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005363 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005364
Owen Andersoneed707b2009-07-24 23:12:02 +00005365 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005366 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005367 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5368 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005369 // Emit an add instruction.
5370 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005371 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005372 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005373 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005374 if (Op->getType() != IntPtrTy)
5375 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005376 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005377 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005378 // We'll let instcombine(mul) convert this to a shl if possible.
5379 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005380 }
5381
5382 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005383 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005384 }
5385 return Result;
5386}
5387
Chris Lattner10c0d912008-04-22 02:53:33 +00005388
Dan Gohman8f080f02009-07-17 22:16:21 +00005389/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5390/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5391/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5392/// be complex, and scales are involved. The above expression would also be
5393/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5394/// This later form is less amenable to optimization though, and we are allowed
5395/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005396///
5397/// If we can't emit an optimized form for this expression, this returns null.
5398///
5399static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5400 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005401 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005402 gep_type_iterator GTI = gep_type_begin(GEP);
5403
5404 // Check to see if this gep only has a single variable index. If so, and if
5405 // any constant indices are a multiple of its scale, then we can compute this
5406 // in terms of the scale of the variable index. For example, if the GEP
5407 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5408 // because the expression will cross zero at the same point.
5409 unsigned i, e = GEP->getNumOperands();
5410 int64_t Offset = 0;
5411 for (i = 1; i != e; ++i, ++GTI) {
5412 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5413 // Compute the aggregate offset of constant indices.
5414 if (CI->isZero()) continue;
5415
5416 // Handle a struct index, which adds its field offset to the pointer.
5417 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5418 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5419 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005420 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005421 Offset += Size*CI->getSExtValue();
5422 }
5423 } else {
5424 // Found our variable index.
5425 break;
5426 }
5427 }
5428
5429 // If there are no variable indices, we must have a constant offset, just
5430 // evaluate it the general way.
5431 if (i == e) return 0;
5432
5433 Value *VariableIdx = GEP->getOperand(i);
5434 // Determine the scale factor of the variable element. For example, this is
5435 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005436 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005437
5438 // Verify that there are no other variable indices. If so, emit the hard way.
5439 for (++i, ++GTI; i != e; ++i, ++GTI) {
5440 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5441 if (!CI) return 0;
5442
5443 // Compute the aggregate offset of constant indices.
5444 if (CI->isZero()) continue;
5445
5446 // Handle a struct index, which adds its field offset to the pointer.
5447 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5448 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5449 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005450 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005451 Offset += Size*CI->getSExtValue();
5452 }
5453 }
5454
5455 // Okay, we know we have a single variable index, which must be a
5456 // pointer/array/vector index. If there is no offset, life is simple, return
5457 // the index.
5458 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5459 if (Offset == 0) {
5460 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5461 // we don't need to bother extending: the extension won't affect where the
5462 // computation crosses zero.
5463 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005464 VariableIdx = new TruncInst(VariableIdx,
5465 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005466 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005467 return VariableIdx;
5468 }
5469
5470 // Otherwise, there is an index. The computation we will do will be modulo
5471 // the pointer size, so get it.
5472 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5473
5474 Offset &= PtrSizeMask;
5475 VariableScale &= PtrSizeMask;
5476
5477 // To do this transformation, any constant index must be a multiple of the
5478 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5479 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5480 // multiple of the variable scale.
5481 int64_t NewOffs = Offset / (int64_t)VariableScale;
5482 if (Offset != NewOffs*(int64_t)VariableScale)
5483 return 0;
5484
5485 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005486 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005487 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005488 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005489 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005490 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005491 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005492 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005493}
5494
5495
Reid Spencere4d87aa2006-12-23 06:05:41 +00005496/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005497/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005498Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005499 ICmpInst::Predicate Cond,
5500 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005501 // Look through bitcasts.
5502 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5503 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005504
Chris Lattner574da9b2005-01-13 20:14:25 +00005505 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005506 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005507 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005508 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005509 // know pointers can't overflow since the gep is inbounds. See if we can
5510 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005511 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5512
5513 // If not, synthesize the offset the hard way.
5514 if (Offset == 0)
5515 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005516 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005517 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005518 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005519 // If the base pointers are different, but the indices are the same, just
5520 // compare the base pointer.
5521 if (PtrBase != GEPRHS->getOperand(0)) {
5522 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005523 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005524 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005525 if (IndicesTheSame)
5526 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5527 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5528 IndicesTheSame = false;
5529 break;
5530 }
5531
5532 // If all indices are the same, just compare the base pointers.
5533 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005534 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005535 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005536
5537 // Otherwise, the base pointers are different and the indices are
5538 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005539 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005540 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005541
Chris Lattnere9d782b2005-01-13 22:25:21 +00005542 // If one of the GEPs has all zero indices, recurse.
5543 bool AllZeros = true;
5544 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5545 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5546 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5547 AllZeros = false;
5548 break;
5549 }
5550 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005551 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5552 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005553
5554 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005555 AllZeros = true;
5556 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5557 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5558 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5559 AllZeros = false;
5560 break;
5561 }
5562 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005563 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005564
Chris Lattner4401c9c2005-01-14 00:20:05 +00005565 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5566 // If the GEPs only differ by one index, compare it.
5567 unsigned NumDifferences = 0; // Keep track of # differences.
5568 unsigned DiffOperand = 0; // The operand that differs.
5569 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5570 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005571 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5572 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005573 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005574 NumDifferences = 2;
5575 break;
5576 } else {
5577 if (NumDifferences++) break;
5578 DiffOperand = i;
5579 }
5580 }
5581
5582 if (NumDifferences == 0) // SAME GEP?
5583 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005584 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005585 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005586
Chris Lattner4401c9c2005-01-14 00:20:05 +00005587 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005588 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5589 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005590 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005591 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005592 }
5593 }
5594
Reid Spencere4d87aa2006-12-23 06:05:41 +00005595 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005596 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005597 if (TD &&
5598 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005599 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5600 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5601 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5602 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005603 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005604 }
5605 }
5606 return 0;
5607}
5608
Chris Lattnera5406232008-05-19 20:18:56 +00005609/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5610///
5611Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5612 Instruction *LHSI,
5613 Constant *RHSC) {
5614 if (!isa<ConstantFP>(RHSC)) return 0;
5615 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5616
5617 // Get the width of the mantissa. We don't want to hack on conversions that
5618 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005619 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005620 if (MantissaWidth == -1) return 0; // Unknown.
5621
5622 // Check to see that the input is converted from an integer type that is small
5623 // enough that preserves all bits. TODO: check here for "known" sign bits.
5624 // 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 +00005625 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005626
5627 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005628 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5629 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005630 ++InputSize;
5631
5632 // If the conversion would lose info, don't hack on this.
5633 if ((int)InputSize > MantissaWidth)
5634 return 0;
5635
5636 // Otherwise, we can potentially simplify the comparison. We know that it
5637 // will always come through as an integer value and we know the constant is
5638 // not a NAN (it would have been previously simplified).
5639 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5640
5641 ICmpInst::Predicate Pred;
5642 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005643 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005644 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005645 case FCmpInst::FCMP_OEQ:
5646 Pred = ICmpInst::ICMP_EQ;
5647 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005648 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005649 case FCmpInst::FCMP_OGT:
5650 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5651 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005652 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005653 case FCmpInst::FCMP_OGE:
5654 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5655 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005656 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005657 case FCmpInst::FCMP_OLT:
5658 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5659 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005660 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005661 case FCmpInst::FCMP_OLE:
5662 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5663 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005664 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005665 case FCmpInst::FCMP_ONE:
5666 Pred = ICmpInst::ICMP_NE;
5667 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005668 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005669 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005670 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005671 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005672 }
5673
5674 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5675
5676 // Now we know that the APFloat is a normal number, zero or inf.
5677
Chris Lattner85162782008-05-20 03:50:52 +00005678 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005679 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005680 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005681
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005682 if (!LHSUnsigned) {
5683 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5684 // and large values.
5685 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5686 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5687 APFloat::rmNearestTiesToEven);
5688 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5689 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5690 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005691 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5692 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005693 }
5694 } else {
5695 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5696 // +INF and large values.
5697 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5698 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5699 APFloat::rmNearestTiesToEven);
5700 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5701 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5702 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005703 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5704 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005705 }
Chris Lattnera5406232008-05-19 20:18:56 +00005706 }
5707
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005708 if (!LHSUnsigned) {
5709 // See if the RHS value is < SignedMin.
5710 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5711 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5712 APFloat::rmNearestTiesToEven);
5713 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5714 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5715 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005716 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5717 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005718 }
Chris Lattnera5406232008-05-19 20:18:56 +00005719 }
5720
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5722 // [0, UMAX], but it may still be fractional. See if it is fractional by
5723 // casting the FP value to the integer value and back, checking for equality.
5724 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005725 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005726 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5727 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005728 if (!RHS.isZero()) {
5729 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005730 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5731 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005732 if (!Equal) {
5733 // If we had a comparison against a fractional value, we have to adjust
5734 // the compare predicate and sometimes the value. RHSC is rounded towards
5735 // zero at this point.
5736 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005737 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005738 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005740 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005741 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005742 case ICmpInst::ICMP_ULE:
5743 // (float)int <= 4.4 --> int <= 4
5744 // (float)int <= -4.4 --> false
5745 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005746 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005747 break;
5748 case ICmpInst::ICMP_SLE:
5749 // (float)int <= 4.4 --> int <= 4
5750 // (float)int <= -4.4 --> int < -4
5751 if (RHS.isNegative())
5752 Pred = ICmpInst::ICMP_SLT;
5753 break;
5754 case ICmpInst::ICMP_ULT:
5755 // (float)int < -4.4 --> false
5756 // (float)int < 4.4 --> int <= 4
5757 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005758 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005759 Pred = ICmpInst::ICMP_ULE;
5760 break;
5761 case ICmpInst::ICMP_SLT:
5762 // (float)int < -4.4 --> int < -4
5763 // (float)int < 4.4 --> int <= 4
5764 if (!RHS.isNegative())
5765 Pred = ICmpInst::ICMP_SLE;
5766 break;
5767 case ICmpInst::ICMP_UGT:
5768 // (float)int > 4.4 --> int > 4
5769 // (float)int > -4.4 --> true
5770 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005771 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005772 break;
5773 case ICmpInst::ICMP_SGT:
5774 // (float)int > 4.4 --> int > 4
5775 // (float)int > -4.4 --> int >= -4
5776 if (RHS.isNegative())
5777 Pred = ICmpInst::ICMP_SGE;
5778 break;
5779 case ICmpInst::ICMP_UGE:
5780 // (float)int >= -4.4 --> true
5781 // (float)int >= 4.4 --> int > 4
5782 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005783 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005784 Pred = ICmpInst::ICMP_UGT;
5785 break;
5786 case ICmpInst::ICMP_SGE:
5787 // (float)int >= -4.4 --> int >= -4
5788 // (float)int >= 4.4 --> int > 4
5789 if (!RHS.isNegative())
5790 Pred = ICmpInst::ICMP_SGT;
5791 break;
5792 }
Chris Lattnera5406232008-05-19 20:18:56 +00005793 }
5794 }
5795
5796 // Lower this FP comparison into an appropriate integer version of the
5797 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005798 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005799}
5800
Reid Spencere4d87aa2006-12-23 06:05:41 +00005801Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5802 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005803 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005804
Chris Lattner58e97462007-01-14 19:42:17 +00005805 // Fold trivial predicates.
5806 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005807 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005808 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005809 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005810
5811 // Simplify 'fcmp pred X, X'
5812 if (Op0 == Op1) {
5813 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005814 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005815 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5816 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5817 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005818 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005819 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5820 case FCmpInst::FCMP_OLT: // True if ordered and less than
5821 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005822 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005823
5824 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5825 case FCmpInst::FCMP_ULT: // True if unordered or less than
5826 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5827 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5828 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5829 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005830 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005831 return &I;
5832
5833 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5834 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5835 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5836 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5837 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5838 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005839 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005840 return &I;
5841 }
5842 }
5843
Reid Spencere4d87aa2006-12-23 06:05:41 +00005844 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005845 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005846
Reid Spencere4d87aa2006-12-23 06:05:41 +00005847 // Handle fcmp with constant RHS
5848 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005849 // If the constant is a nan, see if we can fold the comparison based on it.
5850 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5851 if (CFP->getValueAPF().isNaN()) {
5852 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005853 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005854 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5855 "Comparison must be either ordered or unordered!");
5856 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005857 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005858 }
5859 }
5860
Reid Spencere4d87aa2006-12-23 06:05:41 +00005861 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5862 switch (LHSI->getOpcode()) {
5863 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005864 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5865 // block. If in the same block, we're encouraging jump threading. If
5866 // not, we are just pessimizing the code by making an i1 phi.
5867 if (LHSI->getParent() == I.getParent())
5868 if (Instruction *NV = FoldOpIntoPhi(I))
5869 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005870 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005871 case Instruction::SIToFP:
5872 case Instruction::UIToFP:
5873 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5874 return NV;
5875 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005876 case Instruction::Select:
5877 // If either operand of the select is a constant, we can fold the
5878 // comparison into the select arms, which will cause one to be
5879 // constant folded and the select turned into a bitwise or.
5880 Value *Op1 = 0, *Op2 = 0;
5881 if (LHSI->hasOneUse()) {
5882 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5883 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005884 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005886 Op2 = Builder->CreateFCmp(I.getPredicate(),
5887 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5889 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005890 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005891 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005892 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5893 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005894 }
5895 }
5896
5897 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005898 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005899 break;
5900 }
5901 }
5902
5903 return Changed ? &I : 0;
5904}
5905
5906Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5907 bool Changed = SimplifyCompare(I);
5908 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5909 const Type *Ty = Op0->getType();
5910
5911 // icmp X, X
5912 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005913 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005914 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005915
5916 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005917 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005918
Reid Spencere4d87aa2006-12-23 06:05:41 +00005919 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005920 // addresses never equal each other! We already know that Op0 != Op1.
Victor Hernandez83d63912009-09-18 22:35:49 +00005921 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005922 isa<ConstantPointerNull>(Op0)) &&
Victor Hernandez83d63912009-09-18 22:35:49 +00005923 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005924 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005925 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005926 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005927
Reid Spencere4d87aa2006-12-23 06:05:41 +00005928 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005929 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005930 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005931 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005932 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005933 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005934 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005935 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005936 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005937 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005938
Reid Spencere4d87aa2006-12-23 06:05:41 +00005939 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005940 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005941 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005942 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005943 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005944 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005945 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005946 case ICmpInst::ICMP_SGT:
5947 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005948 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005949 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005950 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005951 return BinaryOperator::CreateAnd(Not, Op0);
5952 }
5953 case ICmpInst::ICMP_UGE:
5954 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5955 // FALL THROUGH
5956 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005957 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005958 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005959 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005960 case ICmpInst::ICMP_SGE:
5961 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5962 // FALL THROUGH
5963 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005964 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005965 return BinaryOperator::CreateOr(Not, Op0);
5966 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005967 }
Chris Lattner8b170942002-08-09 23:47:40 +00005968 }
5969
Dan Gohman1c8491e2009-04-25 17:12:48 +00005970 unsigned BitWidth = 0;
5971 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005972 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5973 else if (Ty->isIntOrIntVector())
5974 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005975
5976 bool isSignBit = false;
5977
Dan Gohman81b28ce2008-09-16 18:46:06 +00005978 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005979 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005980 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005981
Chris Lattnerb6566012008-01-05 01:18:20 +00005982 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5983 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005984 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005985 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005986 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005987 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005988
Dan Gohman81b28ce2008-09-16 18:46:06 +00005989 // If we have an icmp le or icmp ge instruction, turn it into the
5990 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5991 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005992 switch (I.getPredicate()) {
5993 default: break;
5994 case ICmpInst::ICMP_ULE:
5995 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005996 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005997 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005998 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005999 case ICmpInst::ICMP_SLE:
6000 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006001 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006002 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006003 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006004 case ICmpInst::ICMP_UGE:
6005 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006006 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006007 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006008 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006009 case ICmpInst::ICMP_SGE:
6010 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006011 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006012 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006013 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006014 }
6015
Chris Lattner183661e2008-07-11 05:40:05 +00006016 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006017 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006018 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006019 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6020 }
6021
6022 // See if we can fold the comparison based on range information we can get
6023 // by checking whether bits are known to be zero or one in the input.
6024 if (BitWidth != 0) {
6025 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6026 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6027
6028 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006029 isSignBit ? APInt::getSignBit(BitWidth)
6030 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006031 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006032 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006033 if (SimplifyDemandedBits(I.getOperandUse(1),
6034 APInt::getAllOnesValue(BitWidth),
6035 Op1KnownZero, Op1KnownOne, 0))
6036 return &I;
6037
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006038 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006039 // in. Compute the Min, Max and RHS values based on the known bits. For the
6040 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006041 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6042 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6043 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6044 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6045 Op0Min, Op0Max);
6046 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6047 Op1Min, Op1Max);
6048 } else {
6049 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6050 Op0Min, Op0Max);
6051 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6052 Op1Min, Op1Max);
6053 }
6054
Chris Lattner183661e2008-07-11 05:40:05 +00006055 // If Min and Max are known to be the same, then SimplifyDemandedBits
6056 // figured out that the LHS is a constant. Just constant fold this now so
6057 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006058 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006059 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006060 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006061 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006062 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006063 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006064
Chris Lattner183661e2008-07-11 05:40:05 +00006065 // Based on the range information we know about the LHS, see if we can
6066 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006067 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006068 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006069 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006070 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006071 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006072 break;
6073 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006075 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006076 break;
6077 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006079 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006080 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006081 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006083 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6085 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006086 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006087 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088
6089 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6090 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006091 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006092 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006093 }
Chris Lattner84dff672008-07-11 05:08:55 +00006094 break;
6095 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006097 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006099 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100
6101 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006102 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006103 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6104 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006105 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006106 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006107
6108 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6109 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006110 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006111 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 }
Chris Lattner84dff672008-07-11 05:08:55 +00006113 break;
6114 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006116 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006117 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006120 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6122 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006123 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006124 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125 }
Chris Lattner84dff672008-07-11 05:08:55 +00006126 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006127 case ICmpInst::ICMP_SGT:
6128 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006129 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006130 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006131 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132
6133 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006134 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6136 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006137 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006138 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 }
6140 break;
6141 case ICmpInst::ICMP_SGE:
6142 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6143 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 break;
6148 case ICmpInst::ICMP_SLE:
6149 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6150 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006151 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006153 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 break;
6155 case ICmpInst::ICMP_UGE:
6156 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6157 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 break;
6162 case ICmpInst::ICMP_ULE:
6163 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6164 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006165 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006166 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006167 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006168 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006169 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170
6171 // Turn a signed comparison into an unsigned one if both operands
6172 // are known to have the same sign.
6173 if (I.isSignedPredicate() &&
6174 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6175 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006176 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006177 }
6178
6179 // Test if the ICmpInst instruction is used exclusively by a select as
6180 // part of a minimum or maximum operation. If so, refrain from doing
6181 // any other folding. This helps out other analyses which understand
6182 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6183 // and CodeGen. And in this case, at least one of the comparison
6184 // operands has at least one user besides the compare (the select),
6185 // which would often largely negate the benefit of folding anyway.
6186 if (I.hasOneUse())
6187 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6188 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6189 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6190 return 0;
6191
6192 // See if we are doing a comparison between a constant and an instruction that
6193 // can be folded into the comparison.
6194 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006195 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006196 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006197 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006198 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006199 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6200 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006201 }
6202
Chris Lattner01deb9d2007-04-03 17:43:25 +00006203 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006204 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6205 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6206 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006207 case Instruction::GetElementPtr:
6208 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006209 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006210 bool isAllZeros = true;
6211 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6212 if (!isa<Constant>(LHSI->getOperand(i)) ||
6213 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6214 isAllZeros = false;
6215 break;
6216 }
6217 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006218 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006219 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006220 }
6221 break;
6222
Chris Lattner6970b662005-04-23 15:31:55 +00006223 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006224 // Only fold icmp into the PHI if the phi and fcmp are in the same
6225 // block. If in the same block, we're encouraging jump threading. If
6226 // not, we are just pessimizing the code by making an i1 phi.
6227 if (LHSI->getParent() == I.getParent())
6228 if (Instruction *NV = FoldOpIntoPhi(I))
6229 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006230 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006231 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006232 // If either operand of the select is a constant, we can fold the
6233 // comparison into the select arms, which will cause one to be
6234 // constant folded and the select turned into a bitwise or.
6235 Value *Op1 = 0, *Op2 = 0;
6236 if (LHSI->hasOneUse()) {
6237 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6238 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006239 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006240 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006241 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6242 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006243 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6244 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006245 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006246 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006247 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6248 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006249 }
6250 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006251
Chris Lattner6970b662005-04-23 15:31:55 +00006252 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006253 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006254 break;
6255 }
Chris Lattner4802d902007-04-06 18:57:34 +00006256 case Instruction::Malloc:
6257 // If we have (malloc != null), and if the malloc has a single use, we
6258 // can assume it is successful and remove the malloc.
6259 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006260 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006261 return ReplaceInstUsesWith(I,
6262 ConstantInt::get(Type::getInt1Ty(*Context),
6263 !I.isTrueWhenEqual()));
6264 }
6265 break;
6266 case Instruction::Call:
6267 // If we have (malloc != null), and if the malloc has a single use, we
6268 // can assume it is successful and remove the malloc.
6269 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6270 isa<ConstantPointerNull>(RHSC)) {
6271 Worklist.Add(LHSI);
6272 return ReplaceInstUsesWith(I,
6273 ConstantInt::get(Type::getInt1Ty(*Context),
6274 !I.isTrueWhenEqual()));
6275 }
6276 break;
6277 case Instruction::BitCast:
6278 // If we have (malloc != null), and if the malloc has a single use, we
6279 // can assume it is successful and remove the malloc.
6280 CallInst* CI = extractMallocCallFromBitCast(LHSI);
6281 if (CI && CI->hasOneUse() && LHSI->hasOneUse()
6282 && isa<ConstantPointerNull>(RHSC)) {
6283 Worklist.Add(LHSI);
6284 Worklist.Add(CI);
6285 return ReplaceInstUsesWith(I,
6286 ConstantInt::get(Type::getInt1Ty(*Context),
6287 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006288 }
6289 break;
6290 }
Chris Lattner6970b662005-04-23 15:31:55 +00006291 }
6292
Reid Spencere4d87aa2006-12-23 06:05:41 +00006293 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006294 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006295 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006296 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006297 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006298 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6299 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006300 return NI;
6301
Reid Spencere4d87aa2006-12-23 06:05:41 +00006302 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006303 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6304 // now.
6305 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6306 if (isa<PointerType>(Op0->getType()) &&
6307 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006308 // We keep moving the cast from the left operand over to the right
6309 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006310 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006311
Chris Lattner57d86372007-01-06 01:45:59 +00006312 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6313 // so eliminate it as well.
6314 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6315 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006316
Chris Lattnerde90b762003-11-03 04:25:02 +00006317 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006318 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006319 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006320 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006321 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006322 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006323 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006324 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006325 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006326 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006327 }
Chris Lattner57d86372007-01-06 01:45:59 +00006328 }
6329
6330 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006331 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006332 // This comes up when you have code like
6333 // int X = A < B;
6334 // if (X) ...
6335 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006336 // with a constant or another cast from the same type.
6337 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006338 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006339 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006340 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006341
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006342 // See if it's the same type of instruction on the left and right.
6343 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6344 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006345 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006346 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006347 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006348 default: break;
6349 case Instruction::Add:
6350 case Instruction::Sub:
6351 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006352 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006353 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006354 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006355 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6356 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6357 if (CI->getValue().isSignBit()) {
6358 ICmpInst::Predicate Pred = I.isSignedPredicate()
6359 ? I.getUnsignedPredicate()
6360 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006361 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006362 Op1I->getOperand(0));
6363 }
6364
6365 if (CI->getValue().isMaxSignedValue()) {
6366 ICmpInst::Predicate Pred = I.isSignedPredicate()
6367 ? I.getUnsignedPredicate()
6368 : I.getSignedPredicate();
6369 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006370 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006371 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006372 }
6373 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006374 break;
6375 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006376 if (!I.isEquality())
6377 break;
6378
Nick Lewycky5d52c452008-08-21 05:56:10 +00006379 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6380 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6381 // Mask = -1 >> count-trailing-zeros(Cst).
6382 if (!CI->isZero() && !CI->isOne()) {
6383 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006384 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006385 APInt::getLowBitsSet(AP.getBitWidth(),
6386 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006387 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006388 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6389 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006390 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006391 }
6392 }
6393 break;
6394 }
6395 }
6396 }
6397 }
6398
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006399 // ~x < ~y --> y < x
6400 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006401 if (match(Op0, m_Not(m_Value(A))) &&
6402 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006403 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006404 }
6405
Chris Lattner65b72ba2006-09-18 04:22:48 +00006406 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006407 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006408
6409 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006410 if (match(Op0, m_Neg(m_Value(A))) &&
6411 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006412 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006413
Dan Gohman4ae51262009-08-12 16:23:25 +00006414 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006415 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6416 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006417 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006418 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006419 }
6420
Dan Gohman4ae51262009-08-12 16:23:25 +00006421 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006422 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006423 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006424 if (match(B, m_ConstantInt(C1)) &&
6425 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006426 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006427 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006428 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6429 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006430 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006431
6432 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006433 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6434 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6435 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6436 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006437 }
6438 }
6439
Dan Gohman4ae51262009-08-12 16:23:25 +00006440 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006441 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006442 // A == (A^B) -> B == 0
6443 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006444 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006445 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006446 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006447
6448 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006449 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006450 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006451 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006452
6453 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006454 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006455 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006456 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006457
Chris Lattner9c2328e2006-11-14 06:06:06 +00006458 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6459 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006460 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6461 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006462 Value *X = 0, *Y = 0, *Z = 0;
6463
6464 if (A == C) {
6465 X = B; Y = D; Z = A;
6466 } else if (A == D) {
6467 X = B; Y = C; Z = A;
6468 } else if (B == C) {
6469 X = A; Y = D; Z = B;
6470 } else if (B == D) {
6471 X = A; Y = C; Z = B;
6472 }
6473
6474 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006475 Op1 = Builder->CreateXor(X, Y, "tmp");
6476 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006477 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006478 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006479 return &I;
6480 }
6481 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006482 }
Chris Lattner7e708292002-06-25 16:13:24 +00006483 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006484}
6485
Chris Lattner562ef782007-06-20 23:46:26 +00006486
6487/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6488/// and CmpRHS are both known to be integer constants.
6489Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6490 ConstantInt *DivRHS) {
6491 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6492 const APInt &CmpRHSV = CmpRHS->getValue();
6493
6494 // FIXME: If the operand types don't match the type of the divide
6495 // then don't attempt this transform. The code below doesn't have the
6496 // logic to deal with a signed divide and an unsigned compare (and
6497 // vice versa). This is because (x /s C1) <s C2 produces different
6498 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6499 // (x /u C1) <u C2. Simply casting the operands and result won't
6500 // work. :( The if statement below tests that condition and bails
6501 // if it finds it.
6502 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6503 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6504 return 0;
6505 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006506 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006507 if (DivIsSigned && DivRHS->isAllOnesValue())
6508 return 0; // The overflow computation also screws up here
6509 if (DivRHS->isOne())
6510 return 0; // Not worth bothering, and eliminates some funny cases
6511 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006512
6513 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6514 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6515 // C2 (CI). By solving for X we can turn this into a range check
6516 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006517 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006518
6519 // Determine if the product overflows by seeing if the product is
6520 // not equal to the divide. Make sure we do the same kind of divide
6521 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006522 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6523 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006524
6525 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006526 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006527
Chris Lattner1dbfd482007-06-21 18:11:19 +00006528 // Figure out the interval that is being checked. For example, a comparison
6529 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6530 // Compute this interval based on the constants involved and the signedness of
6531 // the compare/divide. This computes a half-open interval, keeping track of
6532 // whether either value in the interval overflows. After analysis each
6533 // overflow variable is set to 0 if it's corresponding bound variable is valid
6534 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6535 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006536 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006537
Chris Lattner562ef782007-06-20 23:46:26 +00006538 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006539 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006540 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006541 HiOverflow = LoOverflow = ProdOV;
6542 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006543 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006544 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006545 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006546 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006547 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006548 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006549 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006550 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6551 HiOverflow = LoOverflow = ProdOV;
6552 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006553 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006554 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006555 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006556 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006557 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6558 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006559 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006560 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006561 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006562 true) ? -1 : 0;
6563 }
Chris Lattner562ef782007-06-20 23:46:26 +00006564 }
Dan Gohman76491272008-02-13 22:09:18 +00006565 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006566 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006567 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006568 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006569 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006570 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6571 HiOverflow = 1; // [INTMIN+1, overflow)
6572 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6573 }
Dan Gohman76491272008-02-13 22:09:18 +00006574 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006575 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006576 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006577 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006578 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006579 LoOverflow = AddWithOverflow(LoBound, HiBound,
6580 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006581 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006582 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6583 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006584 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006585 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006586 }
6587
Chris Lattner1dbfd482007-06-21 18:11:19 +00006588 // Dividing by a negative swaps the condition. LT <-> GT
6589 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006590 }
6591
6592 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006593 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006594 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006595 case ICmpInst::ICMP_EQ:
6596 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006597 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006598 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006599 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006600 ICmpInst::ICMP_UGE, X, LoBound);
6601 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006602 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006603 ICmpInst::ICMP_ULT, X, HiBound);
6604 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006605 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006606 case ICmpInst::ICMP_NE:
6607 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006608 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006609 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006610 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006611 ICmpInst::ICMP_ULT, X, LoBound);
6612 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006613 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006614 ICmpInst::ICMP_UGE, X, HiBound);
6615 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006616 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006617 case ICmpInst::ICMP_ULT:
6618 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006620 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006621 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006622 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006623 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006624 case ICmpInst::ICMP_UGT:
6625 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006626 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006627 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006628 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006629 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006630 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006631 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006632 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006633 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006634 }
6635}
6636
6637
Chris Lattner01deb9d2007-04-03 17:43:25 +00006638/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6639///
6640Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6641 Instruction *LHSI,
6642 ConstantInt *RHS) {
6643 const APInt &RHSV = RHS->getValue();
6644
6645 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006646 case Instruction::Trunc:
6647 if (ICI.isEquality() && LHSI->hasOneUse()) {
6648 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6649 // of the high bits truncated out of x are known.
6650 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6651 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6652 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6653 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6654 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6655
6656 // If all the high bits are known, we can do this xform.
6657 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6658 // Pull in the high bits from known-ones set.
6659 APInt NewRHS(RHS->getValue());
6660 NewRHS.zext(SrcBits);
6661 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006662 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006663 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006664 }
6665 }
6666 break;
6667
Duncan Sands0091bf22007-04-04 06:42:45 +00006668 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006669 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6670 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6671 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006672 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6673 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006674 Value *CompareVal = LHSI->getOperand(0);
6675
6676 // If the sign bit of the XorCST is not set, there is no change to
6677 // the operation, just stop using the Xor.
6678 if (!XorCST->getValue().isNegative()) {
6679 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006680 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006681 return &ICI;
6682 }
6683
6684 // Was the old condition true if the operand is positive?
6685 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6686
6687 // If so, the new one isn't.
6688 isTrueIfPositive ^= true;
6689
6690 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006691 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006692 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006693 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006694 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006695 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006696 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006697
6698 if (LHSI->hasOneUse()) {
6699 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6700 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6701 const APInt &SignBit = XorCST->getValue();
6702 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6703 ? ICI.getUnsignedPredicate()
6704 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006705 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006706 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006707 }
6708
6709 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006710 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006711 const APInt &NotSignBit = XorCST->getValue();
6712 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6713 ? ICI.getUnsignedPredicate()
6714 : ICI.getSignedPredicate();
6715 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006716 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006717 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006718 }
6719 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006720 }
6721 break;
6722 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6723 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6724 LHSI->getOperand(0)->hasOneUse()) {
6725 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6726
6727 // If the LHS is an AND of a truncating cast, we can widen the
6728 // and/compare to be the input width without changing the value
6729 // produced, eliminating a cast.
6730 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6731 // We can do this transformation if either the AND constant does not
6732 // have its sign bit set or if it is an equality comparison.
6733 // Extending a relational comparison when we're checking the sign
6734 // bit would not work.
6735 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006736 (ICI.isEquality() ||
6737 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006738 uint32_t BitWidth =
6739 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6740 APInt NewCST = AndCST->getValue();
6741 NewCST.zext(BitWidth);
6742 APInt NewCI = RHSV;
6743 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006744 Value *NewAnd =
6745 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006746 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006747 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006748 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006749 }
6750 }
6751
6752 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6753 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6754 // happens a LOT in code produced by the C front-end, for bitfield
6755 // access.
6756 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6757 if (Shift && !Shift->isShift())
6758 Shift = 0;
6759
6760 ConstantInt *ShAmt;
6761 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6762 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6763 const Type *AndTy = AndCST->getType(); // Type of the and.
6764
6765 // We can fold this as long as we can't shift unknown bits
6766 // into the mask. This can only happen with signed shift
6767 // rights, as they sign-extend.
6768 if (ShAmt) {
6769 bool CanFold = Shift->isLogicalShift();
6770 if (!CanFold) {
6771 // To test for the bad case of the signed shr, see if any
6772 // of the bits shifted in could be tested after the mask.
6773 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6774 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6775
6776 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6777 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6778 AndCST->getValue()) == 0)
6779 CanFold = true;
6780 }
6781
6782 if (CanFold) {
6783 Constant *NewCst;
6784 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006785 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006786 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006787 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006788
6789 // Check to see if we are shifting out any of the bits being
6790 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006791 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006792 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006793 // If we shifted bits out, the fold is not going to work out.
6794 // As a special case, check to see if this means that the
6795 // result is always true or false now.
6796 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006797 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006799 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006800 } else {
6801 ICI.setOperand(1, NewCst);
6802 Constant *NewAndCST;
6803 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006804 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006805 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006806 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006807 LHSI->setOperand(1, NewAndCST);
6808 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006809 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006810 return &ICI;
6811 }
6812 }
6813 }
6814
6815 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6816 // preferable because it allows the C<<Y expression to be hoisted out
6817 // of a loop if Y is invariant and X is not.
6818 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006819 ICI.isEquality() && !Shift->isArithmeticShift() &&
6820 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006821 // Compute C << Y.
6822 Value *NS;
6823 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006824 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006825 } else {
6826 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006827 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006828 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006829
6830 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006831 Value *NewAnd =
6832 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006833
6834 ICI.setOperand(0, NewAnd);
6835 return &ICI;
6836 }
6837 }
6838 break;
6839
Chris Lattnera0141b92007-07-15 20:42:37 +00006840 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6841 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6842 if (!ShAmt) break;
6843
6844 uint32_t TypeBits = RHSV.getBitWidth();
6845
6846 // Check that the shift amount is in range. If not, don't perform
6847 // undefined shifts. When the shift is visited it will be
6848 // simplified.
6849 if (ShAmt->uge(TypeBits))
6850 break;
6851
6852 if (ICI.isEquality()) {
6853 // If we are comparing against bits always shifted out, the
6854 // comparison cannot succeed.
6855 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006856 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006857 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006858 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6859 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006860 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006861 return ReplaceInstUsesWith(ICI, Cst);
6862 }
6863
6864 if (LHSI->hasOneUse()) {
6865 // Otherwise strength reduce the shift into an and.
6866 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6867 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006868 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006869 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006870
Chris Lattner74381062009-08-30 07:44:24 +00006871 Value *And =
6872 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006873 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006874 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006875 }
6876 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006877
6878 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6879 bool TrueIfSigned = false;
6880 if (LHSI->hasOneUse() &&
6881 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6882 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006883 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006884 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006885 Value *And =
6886 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006887 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006888 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006889 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006890 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006891 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006892
6893 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006894 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006895 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006896 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006897 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006898
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006899 // Check that the shift amount is in range. If not, don't perform
6900 // undefined shifts. When the shift is visited it will be
6901 // simplified.
6902 uint32_t TypeBits = RHSV.getBitWidth();
6903 if (ShAmt->uge(TypeBits))
6904 break;
6905
6906 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006907
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006908 // If we are comparing against bits always shifted out, the
6909 // comparison cannot succeed.
6910 APInt Comp = RHSV << ShAmtVal;
6911 if (LHSI->getOpcode() == Instruction::LShr)
6912 Comp = Comp.lshr(ShAmtVal);
6913 else
6914 Comp = Comp.ashr(ShAmtVal);
6915
6916 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6917 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006918 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006919 return ReplaceInstUsesWith(ICI, Cst);
6920 }
6921
6922 // Otherwise, check to see if the bits shifted out are known to be zero.
6923 // If so, we can compare against the unshifted value:
6924 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006925 if (LHSI->hasOneUse() &&
6926 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006927 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006928 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006929 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006930 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006931
Evan Chengf30752c2008-04-23 00:38:06 +00006932 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006933 // Otherwise strength reduce the shift into an and.
6934 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006935 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006936
Chris Lattner74381062009-08-30 07:44:24 +00006937 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6938 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006939 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006940 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006941 }
6942 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006943 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006944
6945 case Instruction::SDiv:
6946 case Instruction::UDiv:
6947 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6948 // Fold this div into the comparison, producing a range check.
6949 // Determine, based on the divide type, what the range is being
6950 // checked. If there is an overflow on the low or high side, remember
6951 // it, otherwise compute the range [low, hi) bounding the new value.
6952 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006953 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6954 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6955 DivRHS))
6956 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006957 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006958
6959 case Instruction::Add:
6960 // Fold: icmp pred (add, X, C1), C2
6961
6962 if (!ICI.isEquality()) {
6963 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6964 if (!LHSC) break;
6965 const APInt &LHSV = LHSC->getValue();
6966
6967 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6968 .subtract(LHSV);
6969
6970 if (ICI.isSignedPredicate()) {
6971 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006972 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006973 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006974 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006975 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006976 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006977 }
6978 } else {
6979 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006980 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006981 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006982 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006983 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006984 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006985 }
6986 }
6987 }
6988 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006989 }
6990
6991 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6992 if (ICI.isEquality()) {
6993 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6994
6995 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6996 // the second operand is a constant, simplify a bit.
6997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6998 switch (BO->getOpcode()) {
6999 case Instruction::SRem:
7000 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7001 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7002 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7003 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007004 Value *NewRem =
7005 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7006 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007007 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007008 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007009 }
7010 }
7011 break;
7012 case Instruction::Add:
7013 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7014 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7015 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007016 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007017 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007018 } else if (RHSV == 0) {
7019 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7020 // efficiently invertible, or if the add has just this one use.
7021 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7022
Dan Gohman186a6362009-08-12 16:04:34 +00007023 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007024 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007025 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007026 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007027 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007028 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007029 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007030 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007031 }
7032 }
7033 break;
7034 case Instruction::Xor:
7035 // For the xor case, we can xor two constants together, eliminating
7036 // the explicit xor.
7037 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007038 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007039 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007040
7041 // FALLTHROUGH
7042 case Instruction::Sub:
7043 // Replace (([sub|xor] A, B) != 0) with (A != B)
7044 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007045 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007046 BO->getOperand(1));
7047 break;
7048
7049 case Instruction::Or:
7050 // If bits are being or'd in that are not present in the constant we
7051 // are comparing against, then the comparison could never succeed!
7052 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007053 Constant *NotCI = ConstantExpr::getNot(RHS);
7054 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007055 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007056 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007057 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007058 }
7059 break;
7060
7061 case Instruction::And:
7062 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7063 // If bits are being compared against that are and'd out, then the
7064 // comparison can never succeed!
7065 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007066 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007067 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007068 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007069
7070 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7071 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007072 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007073 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007074 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007075
7076 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007077 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007079 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007080 ICmpInst::Predicate pred = isICMP_NE ?
7081 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007082 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007083 }
7084
7085 // ((X & ~7) == 0) --> X < 8
7086 if (RHSV == 0 && isHighOnes(BOC)) {
7087 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007088 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007089 ICmpInst::Predicate pred = isICMP_NE ?
7090 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007091 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092 }
7093 }
7094 default: break;
7095 }
7096 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7097 // Handle icmp {eq|ne} <intrinsic>, intcst.
7098 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007099 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007100 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007101 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007102 return &ICI;
7103 }
7104 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007105 }
7106 return 0;
7107}
7108
7109/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7110/// We only handle extending casts so far.
7111///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007112Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7113 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007114 Value *LHSCIOp = LHSCI->getOperand(0);
7115 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007116 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007117 Value *RHSCIOp;
7118
Chris Lattner8c756c12007-05-05 22:41:33 +00007119 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7120 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007121 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7122 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007123 cast<IntegerType>(DestTy)->getBitWidth()) {
7124 Value *RHSOp = 0;
7125 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007126 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007127 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7128 RHSOp = RHSC->getOperand(0);
7129 // If the pointer types don't match, insert a bitcast.
7130 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007131 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007132 }
7133
7134 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007135 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007136 }
7137
7138 // The code below only handles extension cast instructions, so far.
7139 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007140 if (LHSCI->getOpcode() != Instruction::ZExt &&
7141 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007142 return 0;
7143
Reid Spencere4d87aa2006-12-23 06:05:41 +00007144 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7145 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007146
Reid Spencere4d87aa2006-12-23 06:05:41 +00007147 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007148 // Not an extension from the same type?
7149 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007150 if (RHSCIOp->getType() != LHSCIOp->getType())
7151 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007152
Nick Lewycky4189a532008-01-28 03:48:02 +00007153 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007154 // and the other is a zext), then we can't handle this.
7155 if (CI->getOpcode() != LHSCI->getOpcode())
7156 return 0;
7157
Nick Lewycky4189a532008-01-28 03:48:02 +00007158 // Deal with equality cases early.
7159 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007160 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007161
7162 // A signed comparison of sign extended values simplifies into a
7163 // signed comparison.
7164 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007165 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007166
7167 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007168 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007169 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007170
Reid Spencere4d87aa2006-12-23 06:05:41 +00007171 // If we aren't dealing with a constant on the RHS, exit early
7172 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7173 if (!CI)
7174 return 0;
7175
7176 // Compute the constant that would happen if we truncated to SrcTy then
7177 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007178 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7179 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007180 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007181
7182 // If the re-extended constant didn't change...
7183 if (Res2 == CI) {
7184 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7185 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007186 // %A = sext i16 %X to i32
7187 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007188 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007189 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007190 // because %A may have negative value.
7191 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007192 // However, we allow this when the compare is EQ/NE, because they are
7193 // signless.
7194 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007195 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007196 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197 }
7198
7199 // The re-extended constant changed so the constant cannot be represented
7200 // in the shorter type. Consequently, we cannot emit a simple comparison.
7201
7202 // First, handle some easy cases. We know the result cannot be equal at this
7203 // point so handle the ICI.isEquality() cases
7204 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007205 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007206 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007207 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007208
7209 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7210 // should have been folded away previously and not enter in here.
7211 Value *Result;
7212 if (isSignedCmp) {
7213 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007214 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007215 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007216 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007217 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007218 } else {
7219 // We're performing an unsigned comparison.
7220 if (isSignedExt) {
7221 // We're performing an unsigned comp with a sign extended value.
7222 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007223 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007224 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007225 } else {
7226 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007227 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 }
7229 }
7230
7231 // Finally, return the value computed.
7232 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007233 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007234 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007235
7236 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7237 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7238 "ICmp should be folded!");
7239 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007240 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007241 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007242}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007243
Reid Spencer832254e2007-02-02 02:16:23 +00007244Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7245 return commonShiftTransforms(I);
7246}
7247
7248Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7249 return commonShiftTransforms(I);
7250}
7251
7252Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007253 if (Instruction *R = commonShiftTransforms(I))
7254 return R;
7255
7256 Value *Op0 = I.getOperand(0);
7257
7258 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7259 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7260 if (CSI->isAllOnesValue())
7261 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007262
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007263 // See if we can turn a signed shr into an unsigned shr.
7264 if (MaskedValueIsZero(Op0,
7265 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7266 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7267
7268 // Arithmetic shifting an all-sign-bit value is a no-op.
7269 unsigned NumSignBits = ComputeNumSignBits(Op0);
7270 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7271 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007272
Chris Lattner348f6652007-12-06 01:59:46 +00007273 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007274}
7275
7276Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7277 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007278 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007279
7280 // shl X, 0 == X and shr X, 0 == X
7281 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007282 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7283 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007284 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007285
Reid Spencere4d87aa2006-12-23 06:05:41 +00007286 if (isa<UndefValue>(Op0)) {
7287 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007288 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007289 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007290 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007291 }
7292 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007293 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7294 return ReplaceInstUsesWith(I, Op0);
7295 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007297 }
7298
Dan Gohman9004c8a2009-05-21 02:28:33 +00007299 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007300 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007301 return &I;
7302
Chris Lattner2eefe512004-04-09 19:05:30 +00007303 // Try to fold constant and into select arguments.
7304 if (isa<Constant>(Op0))
7305 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007306 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007307 return R;
7308
Reid Spencerb83eb642006-10-20 07:07:24 +00007309 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007310 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7311 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007312 return 0;
7313}
7314
Reid Spencerb83eb642006-10-20 07:07:24 +00007315Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007316 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007317 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007318
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007319 // See if we can simplify any instructions used by the instruction whose sole
7320 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007321 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007322
Dan Gohmana119de82009-06-14 23:30:43 +00007323 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7324 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007325 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007326 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007327 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007328 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007329 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007330 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007331 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007332 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007333 }
7334
7335 // ((X*C1) << C2) == (X * (C1 << C2))
7336 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7337 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7338 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007339 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007340 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007341
7342 // Try to fold constant and into select arguments.
7343 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7344 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7345 return R;
7346 if (isa<PHINode>(Op0))
7347 if (Instruction *NV = FoldOpIntoPhi(I))
7348 return NV;
7349
Chris Lattner8999dd32007-12-22 09:07:47 +00007350 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7351 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7352 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7353 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7354 // place. Don't try to do this transformation in this case. Also, we
7355 // require that the input operand is a shift-by-constant so that we have
7356 // confidence that the shifts will get folded together. We could do this
7357 // xform in more cases, but it is unlikely to be profitable.
7358 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7359 isa<ConstantInt>(TrOp->getOperand(1))) {
7360 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007361 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007362 // (shift2 (shift1 & 0x00FF), c2)
7363 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007364
7365 // For logical shifts, the truncation has the effect of making the high
7366 // part of the register be zeros. Emulate this by inserting an AND to
7367 // clear the top bits as needed. This 'and' will usually be zapped by
7368 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007369 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7370 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007371 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7372
7373 // The mask we constructed says what the trunc would do if occurring
7374 // between the shifts. We want to know the effect *after* the second
7375 // shift. We know that it is a logical shift by a constant, so adjust the
7376 // mask as appropriate.
7377 if (I.getOpcode() == Instruction::Shl)
7378 MaskV <<= Op1->getZExtValue();
7379 else {
7380 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7381 MaskV = MaskV.lshr(Op1->getZExtValue());
7382 }
7383
Chris Lattner74381062009-08-30 07:44:24 +00007384 // shift1 & 0x00FF
7385 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7386 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007387
7388 // Return the value truncated to the interesting size.
7389 return new TruncInst(And, I.getType());
7390 }
7391 }
7392
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007394 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7395 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7396 Value *V1, *V2;
7397 ConstantInt *CC;
7398 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007399 default: break;
7400 case Instruction::Add:
7401 case Instruction::And:
7402 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007403 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007404 // These operators commute.
7405 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007406 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007407 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007408 m_Specific(Op1)))) {
7409 Value *YS = // (Y << C)
7410 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7411 // (X + (Y << C))
7412 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7413 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007414 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007415 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007416 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007417 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007418
Chris Lattner150f12a2005-09-18 06:30:59 +00007419 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007420 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007421 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007422 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007423 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007424 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007425 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007426 Value *YS = // (Y << C)
7427 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7428 Op0BO->getName());
7429 // X & (CC << C)
7430 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7431 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007432 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007433 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007434 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007435
Reid Spencera07cb7d2007-02-02 14:41:37 +00007436 // FALL THROUGH.
7437 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007438 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007439 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007440 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007441 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007442 Value *YS = // (Y << C)
7443 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7444 // (X + (Y << C))
7445 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7446 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007447 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007448 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007449 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007450 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007451
Chris Lattner13d4ab42006-05-31 21:14:00 +00007452 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007453 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7454 match(Op0BO->getOperand(0),
7455 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007456 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007457 cast<BinaryOperator>(Op0BO->getOperand(0))
7458 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007459 Value *YS = // (Y << C)
7460 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7461 // X & (CC << C)
7462 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7463 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007464
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007465 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007466 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007467
Chris Lattner11021cb2005-09-18 05:12:10 +00007468 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007469 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007470 }
7471
7472
7473 // If the operand is an bitwise operator with a constant RHS, and the
7474 // shift is the only use, we can pull it out of the shift.
7475 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7476 bool isValid = true; // Valid only for And, Or, Xor
7477 bool highBitSet = false; // Transform if high bit of constant set?
7478
7479 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007480 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007481 case Instruction::Add:
7482 isValid = isLeftShift;
7483 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007484 case Instruction::Or:
7485 case Instruction::Xor:
7486 highBitSet = false;
7487 break;
7488 case Instruction::And:
7489 highBitSet = true;
7490 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007491 }
7492
7493 // If this is a signed shift right, and the high bit is modified
7494 // by the logical operation, do not perform the transformation.
7495 // The highBitSet boolean indicates the value of the high bit of
7496 // the constant which would cause it to be modified for this
7497 // operation.
7498 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007499 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007500 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007501
7502 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007503 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007505 Value *NewShift =
7506 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007507 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007508
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007509 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007510 NewRHS);
7511 }
7512 }
7513 }
7514 }
7515
Chris Lattnerad0124c2006-01-06 07:52:12 +00007516 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007517 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7518 if (ShiftOp && !ShiftOp->isShift())
7519 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007520
Reid Spencerb83eb642006-10-20 07:07:24 +00007521 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007522 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007523 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7524 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007525 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7526 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7527 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007528
Zhou Sheng4351c642007-04-02 08:20:41 +00007529 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007530
7531 const IntegerType *Ty = cast<IntegerType>(I.getType());
7532
7533 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007534 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007535 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7536 // saturates.
7537 if (AmtSum >= TypeBits) {
7538 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007539 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007540 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7541 }
7542
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007543 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007544 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007545 }
7546
7547 if (ShiftOp->getOpcode() == Instruction::LShr &&
7548 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007549 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007550 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007551
Chris Lattnerb87056f2007-02-05 00:57:54 +00007552 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007553 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007554 }
7555
7556 if (ShiftOp->getOpcode() == Instruction::AShr &&
7557 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007558 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007559 if (AmtSum >= TypeBits)
7560 AmtSum = TypeBits-1;
7561
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007562 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007563
Zhou Shenge9e03f62007-03-28 15:02:20 +00007564 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007565 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007566 }
7567
Chris Lattnerb87056f2007-02-05 00:57:54 +00007568 // Okay, if we get here, one shift must be left, and the other shift must be
7569 // right. See if the amounts are equal.
7570 if (ShiftAmt1 == ShiftAmt2) {
7571 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7572 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007573 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007574 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007575 }
7576 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7577 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007578 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007579 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007580 }
7581 // We can simplify ((X << C) >>s C) into a trunc + sext.
7582 // NOTE: we could do this for any C, but that would make 'unusual' integer
7583 // types. For now, just stick to ones well-supported by the code
7584 // generators.
7585 const Type *SExtType = 0;
7586 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007587 case 1 :
7588 case 8 :
7589 case 16 :
7590 case 32 :
7591 case 64 :
7592 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007593 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007594 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007595 default: break;
7596 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007597 if (SExtType)
7598 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599 // Otherwise, we can't handle it yet.
7600 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007601 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007602
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007603 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007604 if (I.getOpcode() == Instruction::Shl) {
7605 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7606 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007607 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007608
Reid Spencer55702aa2007-03-25 21:11:44 +00007609 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007610 return BinaryOperator::CreateAnd(Shift,
7611 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007612 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007613
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007614 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007615 if (I.getOpcode() == Instruction::LShr) {
7616 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007617 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007618
Reid Spencerd5e30f02007-03-26 17:18:58 +00007619 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007620 return BinaryOperator::CreateAnd(Shift,
7621 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007622 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007623
7624 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7625 } else {
7626 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007627 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007628
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007629 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007630 if (I.getOpcode() == Instruction::Shl) {
7631 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7632 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007633 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7634 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007635
Reid Spencer55702aa2007-03-25 21:11:44 +00007636 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007637 return BinaryOperator::CreateAnd(Shift,
7638 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007639 }
7640
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007641 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007642 if (I.getOpcode() == Instruction::LShr) {
7643 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007644 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645
Reid Spencer68d27cf2007-03-26 23:45:51 +00007646 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007647 return BinaryOperator::CreateAnd(Shift,
7648 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007649 }
7650
7651 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007652 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007653 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007654 return 0;
7655}
7656
Chris Lattnera1be5662002-05-02 17:06:02 +00007657
Chris Lattnercfd65102005-10-29 04:36:15 +00007658/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7659/// expression. If so, decompose it, returning some value X, such that Val is
7660/// X*Scale+Offset.
7661///
7662static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007663 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007664 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7665 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007666 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007667 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007668 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007669 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007670 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7671 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7672 if (I->getOpcode() == Instruction::Shl) {
7673 // This is a value scaled by '1 << the shift amt'.
7674 Scale = 1U << RHS->getZExtValue();
7675 Offset = 0;
7676 return I->getOperand(0);
7677 } else if (I->getOpcode() == Instruction::Mul) {
7678 // This value is scaled by 'RHS'.
7679 Scale = RHS->getZExtValue();
7680 Offset = 0;
7681 return I->getOperand(0);
7682 } else if (I->getOpcode() == Instruction::Add) {
7683 // We have X+C. Check to see if we really have (X*C2)+C1,
7684 // where C1 is divisible by C2.
7685 unsigned SubScale;
7686 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007687 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7688 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007689 Offset += RHS->getZExtValue();
7690 Scale = SubScale;
7691 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007692 }
7693 }
7694 }
7695
7696 // Otherwise, we can't look past this.
7697 Scale = 1;
7698 Offset = 0;
7699 return Val;
7700}
7701
7702
Chris Lattnerb3f83972005-10-24 06:03:58 +00007703/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7704/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007705Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007706 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007707 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007708
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007709 BuilderTy AllocaBuilder(*Builder);
7710 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7711
Chris Lattnerb53c2382005-10-24 06:22:12 +00007712 // Remove any uses of AI that are dead.
7713 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007714
Chris Lattnerb53c2382005-10-24 06:22:12 +00007715 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7716 Instruction *User = cast<Instruction>(*UI++);
7717 if (isInstructionTriviallyDead(User)) {
7718 while (UI != E && *UI == User)
7719 ++UI; // If this instruction uses AI more than once, don't break UI.
7720
Chris Lattnerb53c2382005-10-24 06:22:12 +00007721 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007722 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007723 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007724 }
7725 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007726
7727 // This requires TargetData to get the alloca alignment and size information.
7728 if (!TD) return 0;
7729
Chris Lattnerb3f83972005-10-24 06:03:58 +00007730 // Get the type really allocated and the type casted to.
7731 const Type *AllocElTy = AI.getAllocatedType();
7732 const Type *CastElTy = PTy->getElementType();
7733 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007734
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007735 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7736 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007737 if (CastElTyAlign < AllocElTyAlign) return 0;
7738
Chris Lattner39387a52005-10-24 06:35:18 +00007739 // If the allocation has multiple uses, only promote it if we are strictly
7740 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007741 // same, we open the door to infinite loops of various kinds. (A reference
7742 // from a dbg.declare doesn't count as a use for this purpose.)
7743 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7744 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007745
Duncan Sands777d2302009-05-09 07:06:46 +00007746 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7747 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007748 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007749
Chris Lattner455fcc82005-10-29 03:19:53 +00007750 // See if we can satisfy the modulus by pulling a scale out of the array
7751 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007752 unsigned ArraySizeScale;
7753 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007754 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007755 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7756 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007757
Chris Lattner455fcc82005-10-29 03:19:53 +00007758 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7759 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007760 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7761 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007762
Chris Lattner455fcc82005-10-29 03:19:53 +00007763 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7764 Value *Amt = 0;
7765 if (Scale == 1) {
7766 Amt = NumElements;
7767 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007768 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007769 // Insert before the alloca, not before the cast.
7770 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007771 }
7772
Jeff Cohen86796be2007-04-04 16:58:57 +00007773 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007774 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007775 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007776 }
7777
Chris Lattnerb3f83972005-10-24 06:03:58 +00007778 AllocationInst *New;
7779 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007780 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007781 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007782 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7783 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007784 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007785
Dale Johannesena0a66372009-03-05 00:39:02 +00007786 // If the allocation has one real use plus a dbg.declare, just remove the
7787 // declare.
7788 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7789 EraseInstFromFunction(*DI);
7790 }
7791 // If the allocation has multiple real uses, insert a cast and change all
7792 // things that used it to use the new cast. This will also hack on CI, but it
7793 // will die soon.
7794 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007795 // New is the allocation instruction, pointer typed. AI is the original
7796 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007797 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007798 AI.replaceAllUsesWith(NewCast);
7799 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007800 return ReplaceInstUsesWith(CI, New);
7801}
7802
Chris Lattner70074e02006-05-13 02:06:03 +00007803/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007804/// and return it as type Ty without inserting any new casts and without
7805/// changing the computed value. This is used by code that tries to decide
7806/// whether promoting or shrinking integer operations to wider or smaller types
7807/// will allow us to eliminate a truncate or extend.
7808///
7809/// This is a truncation operation if Ty is smaller than V->getType(), or an
7810/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007811///
7812/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7813/// should return true if trunc(V) can be computed by computing V in the smaller
7814/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7815/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7816/// efficiently truncated.
7817///
7818/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7819/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7820/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007821bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007822 unsigned CastOpc,
7823 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007824 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007825 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007826 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007827
7828 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007829 if (!I) return false;
7830
Dan Gohman6de29f82009-06-15 22:12:54 +00007831 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007832
Chris Lattner951626b2007-08-02 06:11:14 +00007833 // If this is an extension or truncate, we can often eliminate it.
7834 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7835 // If this is a cast from the destination type, we can trivially eliminate
7836 // it, and this will remove a cast overall.
7837 if (I->getOperand(0)->getType() == Ty) {
7838 // If the first operand is itself a cast, and is eliminable, do not count
7839 // this as an eliminable cast. We would prefer to eliminate those two
7840 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007841 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007842 ++NumCastsRemoved;
7843 return true;
7844 }
7845 }
7846
7847 // We can't extend or shrink something that has multiple uses: doing so would
7848 // require duplicating the instruction in general, which isn't profitable.
7849 if (!I->hasOneUse()) return false;
7850
Evan Chengf35fd542009-01-15 17:01:23 +00007851 unsigned Opc = I->getOpcode();
7852 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007853 case Instruction::Add:
7854 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007855 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007856 case Instruction::And:
7857 case Instruction::Or:
7858 case Instruction::Xor:
7859 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007860 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007861 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007862 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007863 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007864
Eli Friedman070a9812009-07-13 22:46:01 +00007865 case Instruction::UDiv:
7866 case Instruction::URem: {
7867 // UDiv and URem can be truncated if all the truncated bits are zero.
7868 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7869 uint32_t BitWidth = Ty->getScalarSizeInBits();
7870 if (BitWidth < OrigBitWidth) {
7871 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7872 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7873 MaskedValueIsZero(I->getOperand(1), Mask)) {
7874 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7875 NumCastsRemoved) &&
7876 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7877 NumCastsRemoved);
7878 }
7879 }
7880 break;
7881 }
Chris Lattner46b96052006-11-29 07:18:39 +00007882 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007883 // If we are truncating the result of this SHL, and if it's a shift of a
7884 // constant amount, we can always perform a SHL in a smaller type.
7885 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007886 uint32_t BitWidth = Ty->getScalarSizeInBits();
7887 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007888 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007889 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007890 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007891 }
7892 break;
7893 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007894 // If this is a truncate of a logical shr, we can truncate it to a smaller
7895 // lshr iff we know that the bits we would otherwise be shifting in are
7896 // already zeros.
7897 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007898 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7899 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007900 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007901 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007902 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7903 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007904 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007905 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007906 }
7907 }
Chris Lattner46b96052006-11-29 07:18:39 +00007908 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007909 case Instruction::ZExt:
7910 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007911 case Instruction::Trunc:
7912 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007913 // can safely replace it. Note that replacing it does not reduce the number
7914 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007915 if (Opc == CastOpc)
7916 return true;
7917
7918 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007919 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007920 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007921 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007922 case Instruction::Select: {
7923 SelectInst *SI = cast<SelectInst>(I);
7924 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007925 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007926 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007927 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007928 }
Chris Lattner8114b712008-06-18 04:00:49 +00007929 case Instruction::PHI: {
7930 // We can change a phi if we can change all operands.
7931 PHINode *PN = cast<PHINode>(I);
7932 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7933 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007934 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007935 return false;
7936 return true;
7937 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007938 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007939 // TODO: Can handle more cases here.
7940 break;
7941 }
7942
7943 return false;
7944}
7945
7946/// EvaluateInDifferentType - Given an expression that
7947/// CanEvaluateInDifferentType returns true for, actually insert the code to
7948/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007949Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007950 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007951 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007952 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007953 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007954
7955 // Otherwise, it must be an instruction.
7956 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007957 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007958 unsigned Opc = I->getOpcode();
7959 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007960 case Instruction::Add:
7961 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007962 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007963 case Instruction::And:
7964 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007965 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007966 case Instruction::AShr:
7967 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007968 case Instruction::Shl:
7969 case Instruction::UDiv:
7970 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007971 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007972 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007973 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007974 break;
7975 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007976 case Instruction::Trunc:
7977 case Instruction::ZExt:
7978 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007979 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007980 // just return the source. There's no need to insert it because it is not
7981 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007982 if (I->getOperand(0)->getType() == Ty)
7983 return I->getOperand(0);
7984
Chris Lattner8114b712008-06-18 04:00:49 +00007985 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007986 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007987 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007988 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007989 case Instruction::Select: {
7990 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7991 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7992 Res = SelectInst::Create(I->getOperand(0), True, False);
7993 break;
7994 }
Chris Lattner8114b712008-06-18 04:00:49 +00007995 case Instruction::PHI: {
7996 PHINode *OPN = cast<PHINode>(I);
7997 PHINode *NPN = PHINode::Create(Ty);
7998 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7999 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8000 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8001 }
8002 Res = NPN;
8003 break;
8004 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008005 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008006 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008007 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008008 break;
8009 }
8010
Chris Lattner8114b712008-06-18 04:00:49 +00008011 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008012 return InsertNewInstBefore(Res, *I);
8013}
8014
Reid Spencer3da59db2006-11-27 01:05:10 +00008015/// @brief Implement the transforms common to all CastInst visitors.
8016Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008017 Value *Src = CI.getOperand(0);
8018
Dan Gohman23d9d272007-05-11 21:10:54 +00008019 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008020 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008021 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008022 if (Instruction::CastOps opc =
8023 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8024 // The first cast (CSrc) is eliminable so we need to fix up or replace
8025 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008026 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008027 }
8028 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008029
Reid Spencer3da59db2006-11-27 01:05:10 +00008030 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008031 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8032 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8033 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008034
8035 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008036 if (isa<PHINode>(Src))
8037 if (Instruction *NV = FoldOpIntoPhi(CI))
8038 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008039
Reid Spencer3da59db2006-11-27 01:05:10 +00008040 return 0;
8041}
8042
Chris Lattner46cd5a12009-01-09 05:44:56 +00008043/// FindElementAtOffset - Given a type and a constant offset, determine whether
8044/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008045/// the specified offset. If so, fill them into NewIndices and return the
8046/// resultant element type, otherwise return null.
8047static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8048 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008049 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008050 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008051 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008052 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008053
8054 // Start with the index over the outer type. Note that the type size
8055 // might be zero (even if the offset isn't zero) if the indexed type
8056 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008057 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008058 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008059 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008060 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008061 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008062
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008063 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008064 if (Offset < 0) {
8065 --FirstIdx;
8066 Offset += TySize;
8067 assert(Offset >= 0);
8068 }
8069 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8070 }
8071
Owen Andersoneed707b2009-07-24 23:12:02 +00008072 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008073
8074 // Index into the types. If we fail, set OrigBase to null.
8075 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008076 // Indexing into tail padding between struct/array elements.
8077 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008078 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008079
Chris Lattner46cd5a12009-01-09 05:44:56 +00008080 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8081 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008082 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8083 "Offset must stay within the indexed type");
8084
Chris Lattner46cd5a12009-01-09 05:44:56 +00008085 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008086 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008087
8088 Offset -= SL->getElementOffset(Elt);
8089 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008090 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008091 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008092 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008093 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008094 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008095 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008096 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008097 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008098 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008099 }
8100 }
8101
Chris Lattner3914f722009-01-24 01:00:13 +00008102 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008103}
8104
Chris Lattnerd3e28342007-04-27 17:44:50 +00008105/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8106Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8107 Value *Src = CI.getOperand(0);
8108
Chris Lattnerd3e28342007-04-27 17:44:50 +00008109 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008110 // If casting the result of a getelementptr instruction with no offset, turn
8111 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008112 if (GEP->hasAllZeroIndices()) {
8113 // Changing the cast operand is usually not a good idea but it is safe
8114 // here because the pointer operand is being replaced with another
8115 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008116 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008117 CI.setOperand(0, GEP->getOperand(0));
8118 return &CI;
8119 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008120
8121 // If the GEP has a single use, and the base pointer is a bitcast, and the
8122 // GEP computes a constant offset, see if we can convert these three
8123 // instructions into fewer. This typically happens with unions and other
8124 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008125 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008126 if (GEP->hasAllConstantIndices()) {
8127 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008128 ConstantInt *OffsetV =
8129 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008130 int64_t Offset = OffsetV->getSExtValue();
8131
8132 // Get the base pointer input of the bitcast, and the type it points to.
8133 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8134 const Type *GEPIdxTy =
8135 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008136 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008137 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008138 // If we were able to index down into an element, create the GEP
8139 // and bitcast the result. This eliminates one bitcast, potentially
8140 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008141 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8142 Builder->CreateInBoundsGEP(OrigBase,
8143 NewIndices.begin(), NewIndices.end()) :
8144 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008145 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008146
Chris Lattner46cd5a12009-01-09 05:44:56 +00008147 if (isa<BitCastInst>(CI))
8148 return new BitCastInst(NGEP, CI.getType());
8149 assert(isa<PtrToIntInst>(CI));
8150 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008151 }
8152 }
8153 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008154 }
8155
8156 return commonCastTransforms(CI);
8157}
8158
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008159/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8160/// type like i42. We don't want to introduce operations on random non-legal
8161/// integer types where they don't already exist in the code. In the future,
8162/// we should consider making this based off target-data, so that 32-bit targets
8163/// won't get i64 operations etc.
8164static bool isSafeIntegerType(const Type *Ty) {
8165 switch (Ty->getPrimitiveSizeInBits()) {
8166 case 8:
8167 case 16:
8168 case 32:
8169 case 64:
8170 return true;
8171 default:
8172 return false;
8173 }
8174}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008175
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008176/// commonIntCastTransforms - This function implements the common transforms
8177/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008178Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8179 if (Instruction *Result = commonCastTransforms(CI))
8180 return Result;
8181
8182 Value *Src = CI.getOperand(0);
8183 const Type *SrcTy = Src->getType();
8184 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008185 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8186 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008187
Reid Spencer3da59db2006-11-27 01:05:10 +00008188 // See if we can simplify any instructions used by the LHS whose sole
8189 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008190 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008191 return &CI;
8192
8193 // If the source isn't an instruction or has more than one use then we
8194 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008195 Instruction *SrcI = dyn_cast<Instruction>(Src);
8196 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008197 return 0;
8198
Chris Lattnerc739cd62007-03-03 05:27:34 +00008199 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008200 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008201 // Only do this if the dest type is a simple type, don't convert the
8202 // expression tree to something weird like i93 unless the source is also
8203 // strange.
8204 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008205 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8206 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008207 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008208 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008209 // eliminates the cast, so it is always a win. If this is a zero-extension,
8210 // we need to do an AND to maintain the clear top-part of the computation,
8211 // so we require that the input have eliminated at least one cast. If this
8212 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008213 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008214 bool DoXForm = false;
8215 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008216 switch (CI.getOpcode()) {
8217 default:
8218 // All the others use floating point so we shouldn't actually
8219 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008220 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008221 case Instruction::Trunc:
8222 DoXForm = true;
8223 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008224 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008225 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008226 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008227 // If it's unnecessary to issue an AND to clear the high bits, it's
8228 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008229 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008230 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8231 if (MaskedValueIsZero(TryRes, Mask))
8232 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008233
8234 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008235 if (TryI->use_empty())
8236 EraseInstFromFunction(*TryI);
8237 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008238 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008239 }
Evan Chengf35fd542009-01-15 17:01:23 +00008240 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008241 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008242 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008243 // If we do not have to emit the truncate + sext pair, then it's always
8244 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008245 //
8246 // It's not safe to eliminate the trunc + sext pair if one of the
8247 // eliminated cast is a truncate. e.g.
8248 // t2 = trunc i32 t1 to i16
8249 // t3 = sext i16 t2 to i32
8250 // !=
8251 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008252 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008253 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8254 if (NumSignBits > (DestBitSize - SrcBitSize))
8255 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008256
8257 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008258 if (TryI->use_empty())
8259 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008260 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008261 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008262 }
Evan Chengf35fd542009-01-15 17:01:23 +00008263 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008264
8265 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008266 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8267 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008268 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8269 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008270 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008271 // Just replace this cast with the result.
8272 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008273
Reid Spencer3da59db2006-11-27 01:05:10 +00008274 assert(Res->getType() == DestTy);
8275 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008276 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008277 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008278 // Just replace this cast with the result.
8279 return ReplaceInstUsesWith(CI, Res);
8280 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008282
8283 // If the high bits are already zero, just replace this cast with the
8284 // result.
8285 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8286 if (MaskedValueIsZero(Res, Mask))
8287 return ReplaceInstUsesWith(CI, Res);
8288
8289 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008290 Constant *C = ConstantInt::get(*Context,
8291 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008292 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008294 case Instruction::SExt: {
8295 // If the high bits are already filled with sign bit, just replace this
8296 // cast with the result.
8297 unsigned NumSignBits = ComputeNumSignBits(Res);
8298 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008299 return ReplaceInstUsesWith(CI, Res);
8300
Reid Spencer3da59db2006-11-27 01:05:10 +00008301 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008302 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008303 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008304 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008305 }
8306 }
8307
8308 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8309 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8310
8311 switch (SrcI->getOpcode()) {
8312 case Instruction::Add:
8313 case Instruction::Mul:
8314 case Instruction::And:
8315 case Instruction::Or:
8316 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008317 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008318 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8319 // Don't insert two casts unless at least one can be eliminated.
8320 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008321 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008322 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8323 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008324 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008325 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008326 }
8327 }
8328
8329 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8330 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8331 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008332 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008333 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008334 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008335 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008336 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008337 }
8338 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008339
Eli Friedman65445c52009-07-13 21:45:57 +00008340 case Instruction::Shl: {
8341 // Canonicalize trunc inside shl, if we can.
8342 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8343 if (CI && DestBitSize < SrcBitSize &&
8344 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008345 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8346 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008347 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008348 }
8349 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008350 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008351 }
8352 return 0;
8353}
8354
Chris Lattner8a9f5712007-04-11 06:57:46 +00008355Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008356 if (Instruction *Result = commonIntCastTransforms(CI))
8357 return Result;
8358
8359 Value *Src = CI.getOperand(0);
8360 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008361 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8362 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008363
8364 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008365 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008366 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008367 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008368 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008369 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008370 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008371
Chris Lattner4f9797d2009-03-24 18:15:30 +00008372 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8373 ConstantInt *ShAmtV = 0;
8374 Value *ShiftOp = 0;
8375 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008376 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008377 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8378
8379 // Get a mask for the bits shifting in.
8380 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8381 if (MaskedValueIsZero(ShiftOp, Mask)) {
8382 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008383 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008384
8385 // Okay, we can shrink this. Truncate the input, then return a new
8386 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008387 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008388 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008389 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008390 }
8391 }
8392
8393 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008394}
8395
Evan Chengb98a10e2008-03-24 00:21:34 +00008396/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8397/// in order to eliminate the icmp.
8398Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8399 bool DoXform) {
8400 // If we are just checking for a icmp eq of a single bit and zext'ing it
8401 // to an integer, then shift the bit to the appropriate place and then
8402 // cast to integer to avoid the comparison.
8403 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8404 const APInt &Op1CV = Op1C->getValue();
8405
8406 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8407 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8408 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8409 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8410 if (!DoXform) return ICI;
8411
8412 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008413 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008414 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008415 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008416 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008417 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008418
8419 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008420 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008421 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008422 }
8423
8424 return ReplaceInstUsesWith(CI, In);
8425 }
8426
8427
8428
8429 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8430 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8431 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8432 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8433 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8434 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8435 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8436 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8437 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8438 // This only works for EQ and NE
8439 ICI->isEquality()) {
8440 // If Op1C some other power of two, convert:
8441 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8442 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8443 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8444 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8445
8446 APInt KnownZeroMask(~KnownZero);
8447 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8448 if (!DoXform) return ICI;
8449
8450 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8451 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8452 // (X&4) == 2 --> false
8453 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008454 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008455 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008456 return ReplaceInstUsesWith(CI, Res);
8457 }
8458
8459 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8460 Value *In = ICI->getOperand(0);
8461 if (ShiftAmt) {
8462 // Perform a logical shr by shiftamt.
8463 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008464 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8465 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008466 }
8467
8468 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008469 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008470 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008471 }
8472
8473 if (CI.getType() == In->getType())
8474 return ReplaceInstUsesWith(CI, In);
8475 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008476 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008477 }
8478 }
8479 }
8480
8481 return 0;
8482}
8483
Chris Lattner8a9f5712007-04-11 06:57:46 +00008484Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008485 // If one of the common conversion will work ..
8486 if (Instruction *Result = commonIntCastTransforms(CI))
8487 return Result;
8488
8489 Value *Src = CI.getOperand(0);
8490
Chris Lattnera84f47c2009-02-17 20:47:23 +00008491 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8492 // types and if the sizes are just right we can convert this into a logical
8493 // 'and' which will be much cheaper than the pair of casts.
8494 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8495 // Get the sizes of the types involved. We know that the intermediate type
8496 // will be smaller than A or C, but don't know the relation between A and C.
8497 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008498 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8499 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8500 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008501 // If we're actually extending zero bits, then if
8502 // SrcSize < DstSize: zext(a & mask)
8503 // SrcSize == DstSize: a & mask
8504 // SrcSize > DstSize: trunc(a) & mask
8505 if (SrcSize < DstSize) {
8506 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008507 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008508 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008509 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008510 }
8511
8512 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008513 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008514 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008515 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008516 }
8517 if (SrcSize > DstSize) {
8518 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008519 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008520 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008521 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008522 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008523 }
8524 }
8525
Evan Chengb98a10e2008-03-24 00:21:34 +00008526 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8527 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008528
Evan Chengb98a10e2008-03-24 00:21:34 +00008529 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8530 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8531 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8532 // of the (zext icmp) will be transformed.
8533 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8534 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8535 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8536 (transformZExtICmp(LHS, CI, false) ||
8537 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008538 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8539 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008540 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008541 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008542 }
8543
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008544 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008545 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8546 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8547 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8548 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008549 if (TI0->getType() == CI.getType())
8550 return
8551 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008552 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008553 }
8554
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008555 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8556 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8557 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8558 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8559 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8560 And->getOperand(1) == C)
8561 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8562 Value *TI0 = TI->getOperand(0);
8563 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008564 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008565 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008566 return BinaryOperator::CreateXor(NewAnd, ZC);
8567 }
8568 }
8569
Reid Spencer3da59db2006-11-27 01:05:10 +00008570 return 0;
8571}
8572
Chris Lattner8a9f5712007-04-11 06:57:46 +00008573Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008574 if (Instruction *I = commonIntCastTransforms(CI))
8575 return I;
8576
Chris Lattner8a9f5712007-04-11 06:57:46 +00008577 Value *Src = CI.getOperand(0);
8578
Dan Gohman1975d032008-10-30 20:40:10 +00008579 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008580 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008581 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008582 Constant::getAllOnesValue(CI.getType()),
8583 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008584
8585 // See if the value being truncated is already sign extended. If so, just
8586 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008587 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008588 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008589 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8590 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8591 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008592 unsigned NumSignBits = ComputeNumSignBits(Op);
8593
8594 if (OpBits == DestBits) {
8595 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8596 // bits, it is already ready.
8597 if (NumSignBits > DestBits-MidBits)
8598 return ReplaceInstUsesWith(CI, Op);
8599 } else if (OpBits < DestBits) {
8600 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8601 // bits, just sext from i32.
8602 if (NumSignBits > OpBits-MidBits)
8603 return new SExtInst(Op, CI.getType(), "tmp");
8604 } else {
8605 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8606 // bits, just truncate to i32.
8607 if (NumSignBits > OpBits-MidBits)
8608 return new TruncInst(Op, CI.getType(), "tmp");
8609 }
8610 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008611
8612 // If the input is a shl/ashr pair of a same constant, then this is a sign
8613 // extension from a smaller value. If we could trust arbitrary bitwidth
8614 // integers, we could turn this into a truncate to the smaller bit and then
8615 // use a sext for the whole extension. Since we don't, look deeper and check
8616 // for a truncate. If the source and dest are the same type, eliminate the
8617 // trunc and extend and just do shifts. For example, turn:
8618 // %a = trunc i32 %i to i8
8619 // %b = shl i8 %a, 6
8620 // %c = ashr i8 %b, 6
8621 // %d = sext i8 %c to i32
8622 // into:
8623 // %a = shl i32 %i, 30
8624 // %d = ashr i32 %a, 30
8625 Value *A = 0;
8626 ConstantInt *BA = 0, *CA = 0;
8627 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008628 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008629 BA == CA && isa<TruncInst>(A)) {
8630 Value *I = cast<TruncInst>(A)->getOperand(0);
8631 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008632 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8633 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008634 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008635 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008636 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008637 return BinaryOperator::CreateAShr(I, ShAmtV);
8638 }
8639 }
8640
Chris Lattnerba417832007-04-11 06:12:58 +00008641 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008642}
8643
Chris Lattnerb7530652008-01-27 05:29:54 +00008644/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8645/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008646static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008647 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008648 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008649 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008650 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8651 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008652 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008653 return 0;
8654}
8655
8656/// LookThroughFPExtensions - If this is an fp extension instruction, look
8657/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008658static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008659 if (Instruction *I = dyn_cast<Instruction>(V))
8660 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008661 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008662
8663 // If this value is a constant, return the constant in the smallest FP type
8664 // that can accurately represent it. This allows us to turn
8665 // (float)((double)X+2.0) into x+2.0f.
8666 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008667 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008668 return V; // No constant folding of this.
8669 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008670 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008671 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008672 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008673 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008674 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008675 return V;
8676 // Don't try to shrink to various long double types.
8677 }
8678
8679 return V;
8680}
8681
8682Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8683 if (Instruction *I = commonCastTransforms(CI))
8684 return I;
8685
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008686 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008687 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008688 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008689 // many builtins (sqrt, etc).
8690 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8691 if (OpI && OpI->hasOneUse()) {
8692 switch (OpI->getOpcode()) {
8693 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008694 case Instruction::FAdd:
8695 case Instruction::FSub:
8696 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008697 case Instruction::FDiv:
8698 case Instruction::FRem:
8699 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008700 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8701 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008702 if (LHSTrunc->getType() != SrcTy &&
8703 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008704 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008705 // If the source types were both smaller than the destination type of
8706 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008707 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8708 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008709 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8710 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008711 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008712 }
8713 }
8714 break;
8715 }
8716 }
8717 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008718}
8719
8720Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8721 return commonCastTransforms(CI);
8722}
8723
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008724Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008725 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8726 if (OpI == 0)
8727 return commonCastTransforms(FI);
8728
8729 // fptoui(uitofp(X)) --> X
8730 // fptoui(sitofp(X)) --> X
8731 // This is safe if the intermediate type has enough bits in its mantissa to
8732 // accurately represent all values of X. For example, do not do this with
8733 // i64->float->i64. This is also safe for sitofp case, because any negative
8734 // 'X' value would cause an undefined result for the fptoui.
8735 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8736 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008737 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008738 OpI->getType()->getFPMantissaWidth())
8739 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008740
8741 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008742}
8743
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008744Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008745 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8746 if (OpI == 0)
8747 return commonCastTransforms(FI);
8748
8749 // fptosi(sitofp(X)) --> X
8750 // fptosi(uitofp(X)) --> X
8751 // This is safe if the intermediate type has enough bits in its mantissa to
8752 // accurately represent all values of X. For example, do not do this with
8753 // i64->float->i64. This is also safe for sitofp case, because any negative
8754 // 'X' value would cause an undefined result for the fptoui.
8755 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8756 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008757 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008758 OpI->getType()->getFPMantissaWidth())
8759 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008760
8761 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008762}
8763
8764Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8765 return commonCastTransforms(CI);
8766}
8767
8768Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8769 return commonCastTransforms(CI);
8770}
8771
Chris Lattnera0e69692009-03-24 18:35:40 +00008772Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8773 // If the destination integer type is smaller than the intptr_t type for
8774 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8775 // trunc to be exposed to other transforms. Don't do this for extending
8776 // ptrtoint's, because we don't know if the target sign or zero extends its
8777 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008778 if (TD &&
8779 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008780 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8781 TD->getIntPtrType(CI.getContext()),
8782 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008783 return new TruncInst(P, CI.getType());
8784 }
8785
Chris Lattnerd3e28342007-04-27 17:44:50 +00008786 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008787}
8788
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008789Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008790 // If the source integer type is larger than the intptr_t type for
8791 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8792 // allows the trunc to be exposed to other transforms. Don't do this for
8793 // extending inttoptr's, because we don't know if the target sign or zero
8794 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008795 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008796 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008797 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8798 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008799 return new IntToPtrInst(P, CI.getType());
8800 }
8801
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008802 if (Instruction *I = commonCastTransforms(CI))
8803 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008804
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008805 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008806}
8807
Chris Lattnerd3e28342007-04-27 17:44:50 +00008808Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008809 // If the operands are integer typed then apply the integer transforms,
8810 // otherwise just apply the common ones.
8811 Value *Src = CI.getOperand(0);
8812 const Type *SrcTy = Src->getType();
8813 const Type *DestTy = CI.getType();
8814
Eli Friedman7e25d452009-07-13 20:53:00 +00008815 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008816 if (Instruction *I = commonPointerCastTransforms(CI))
8817 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008818 } else {
8819 if (Instruction *Result = commonCastTransforms(CI))
8820 return Result;
8821 }
8822
8823
8824 // Get rid of casts from one type to the same type. These are useless and can
8825 // be replaced by the operand.
8826 if (DestTy == Src->getType())
8827 return ReplaceInstUsesWith(CI, Src);
8828
Reid Spencer3da59db2006-11-27 01:05:10 +00008829 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008830 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8831 const Type *DstElTy = DstPTy->getElementType();
8832 const Type *SrcElTy = SrcPTy->getElementType();
8833
Nate Begeman83ad90a2008-03-31 00:22:16 +00008834 // If the address spaces don't match, don't eliminate the bitcast, which is
8835 // required for changing types.
8836 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8837 return 0;
8838
Victor Hernandez83d63912009-09-18 22:35:49 +00008839 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008840 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008841 // There is no need to modify malloc calls because it is their bitcast that
8842 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008843 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8844 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8845 return V;
8846
Chris Lattnerd717c182007-05-05 22:32:24 +00008847 // If the source and destination are pointers, and this cast is equivalent
8848 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008849 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008850 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008851 unsigned NumZeros = 0;
8852 while (SrcElTy != DstElTy &&
8853 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8854 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8855 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8856 ++NumZeros;
8857 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008858
Chris Lattnerd3e28342007-04-27 17:44:50 +00008859 // If we found a path from the src to dest, create the getelementptr now.
8860 if (SrcElTy == DstElTy) {
8861 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008862 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8863 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008864 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008865 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008866
Eli Friedman2451a642009-07-18 23:06:53 +00008867 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8868 if (DestVTy->getNumElements() == 1) {
8869 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008870 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008871 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008872 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008873 }
8874 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8875 }
8876 }
8877
8878 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8879 if (SrcVTy->getNumElements() == 1) {
8880 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008881 Value *Elem =
8882 Builder->CreateExtractElement(Src,
8883 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008884 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8885 }
8886 }
8887 }
8888
Reid Spencer3da59db2006-11-27 01:05:10 +00008889 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8890 if (SVI->hasOneUse()) {
8891 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8892 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008893 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008894 cast<VectorType>(DestTy)->getNumElements() ==
8895 SVI->getType()->getNumElements() &&
8896 SVI->getType()->getNumElements() ==
8897 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008898 CastInst *Tmp;
8899 // If either of the operands is a cast from CI.getType(), then
8900 // evaluating the shuffle in the casted destination's type will allow
8901 // us to eliminate at least one cast.
8902 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8903 Tmp->getOperand(0)->getType() == DestTy) ||
8904 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8905 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008906 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8907 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008908 // Return a new shuffle vector. Use the same element ID's, as we
8909 // know the vector types match #elts.
8910 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008911 }
8912 }
8913 }
8914 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008915 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008916}
8917
Chris Lattnere576b912004-04-09 23:46:01 +00008918/// GetSelectFoldableOperands - We want to turn code that looks like this:
8919/// %C = or %A, %B
8920/// %D = select %cond, %C, %A
8921/// into:
8922/// %C = select %cond, %B, 0
8923/// %D = or %A, %C
8924///
8925/// Assuming that the specified instruction is an operand to the select, return
8926/// a bitmask indicating which operands of this instruction are foldable if they
8927/// equal the other incoming value of the select.
8928///
8929static unsigned GetSelectFoldableOperands(Instruction *I) {
8930 switch (I->getOpcode()) {
8931 case Instruction::Add:
8932 case Instruction::Mul:
8933 case Instruction::And:
8934 case Instruction::Or:
8935 case Instruction::Xor:
8936 return 3; // Can fold through either operand.
8937 case Instruction::Sub: // Can only fold on the amount subtracted.
8938 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008939 case Instruction::LShr:
8940 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008941 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008942 default:
8943 return 0; // Cannot fold
8944 }
8945}
8946
8947/// GetSelectFoldableConstant - For the same transformation as the previous
8948/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008949static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008950 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008951 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008952 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008953 case Instruction::Add:
8954 case Instruction::Sub:
8955 case Instruction::Or:
8956 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008957 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008958 case Instruction::LShr:
8959 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008960 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008961 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008962 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008963 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008964 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008965 }
8966}
8967
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008968/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8969/// have the same opcode and only one use each. Try to simplify this.
8970Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8971 Instruction *FI) {
8972 if (TI->getNumOperands() == 1) {
8973 // If this is a non-volatile load or a cast from the same type,
8974 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008975 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008976 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8977 return 0;
8978 } else {
8979 return 0; // unknown unary op.
8980 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008981
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008982 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008983 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008984 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008985 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008986 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008987 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008988 }
8989
Reid Spencer832254e2007-02-02 02:16:23 +00008990 // Only handle binary operators here.
8991 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008992 return 0;
8993
8994 // Figure out if the operations have any operands in common.
8995 Value *MatchOp, *OtherOpT, *OtherOpF;
8996 bool MatchIsOpZero;
8997 if (TI->getOperand(0) == FI->getOperand(0)) {
8998 MatchOp = TI->getOperand(0);
8999 OtherOpT = TI->getOperand(1);
9000 OtherOpF = FI->getOperand(1);
9001 MatchIsOpZero = true;
9002 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9003 MatchOp = TI->getOperand(1);
9004 OtherOpT = TI->getOperand(0);
9005 OtherOpF = FI->getOperand(0);
9006 MatchIsOpZero = false;
9007 } else if (!TI->isCommutative()) {
9008 return 0;
9009 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9010 MatchOp = TI->getOperand(0);
9011 OtherOpT = TI->getOperand(1);
9012 OtherOpF = FI->getOperand(0);
9013 MatchIsOpZero = true;
9014 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9015 MatchOp = TI->getOperand(1);
9016 OtherOpT = TI->getOperand(0);
9017 OtherOpF = FI->getOperand(1);
9018 MatchIsOpZero = true;
9019 } else {
9020 return 0;
9021 }
9022
9023 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009024 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9025 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009026 InsertNewInstBefore(NewSI, SI);
9027
9028 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9029 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009030 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009031 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009032 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009033 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009034 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009035 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009036}
9037
Evan Chengde621922009-03-31 20:42:45 +00009038static bool isSelect01(Constant *C1, Constant *C2) {
9039 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9040 if (!C1I)
9041 return false;
9042 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9043 if (!C2I)
9044 return false;
9045 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9046}
9047
9048/// FoldSelectIntoOp - Try fold the select into one of the operands to
9049/// facilitate further optimization.
9050Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9051 Value *FalseVal) {
9052 // See the comment above GetSelectFoldableOperands for a description of the
9053 // transformation we are doing here.
9054 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9055 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9056 !isa<Constant>(FalseVal)) {
9057 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9058 unsigned OpToFold = 0;
9059 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9060 OpToFold = 1;
9061 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9062 OpToFold = 2;
9063 }
9064
9065 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009066 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009067 Value *OOp = TVI->getOperand(2-OpToFold);
9068 // Avoid creating select between 2 constants unless it's selecting
9069 // between 0 and 1.
9070 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9071 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9072 InsertNewInstBefore(NewSel, SI);
9073 NewSel->takeName(TVI);
9074 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9075 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009076 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009077 }
9078 }
9079 }
9080 }
9081 }
9082
9083 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9084 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9085 !isa<Constant>(TrueVal)) {
9086 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9087 unsigned OpToFold = 0;
9088 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9089 OpToFold = 1;
9090 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9091 OpToFold = 2;
9092 }
9093
9094 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009095 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009096 Value *OOp = FVI->getOperand(2-OpToFold);
9097 // Avoid creating select between 2 constants unless it's selecting
9098 // between 0 and 1.
9099 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9100 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9101 InsertNewInstBefore(NewSel, SI);
9102 NewSel->takeName(FVI);
9103 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9104 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009105 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009106 }
9107 }
9108 }
9109 }
9110 }
9111
9112 return 0;
9113}
9114
Dan Gohman81b28ce2008-09-16 18:46:06 +00009115/// visitSelectInstWithICmp - Visit a SelectInst that has an
9116/// ICmpInst as its first operand.
9117///
9118Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9119 ICmpInst *ICI) {
9120 bool Changed = false;
9121 ICmpInst::Predicate Pred = ICI->getPredicate();
9122 Value *CmpLHS = ICI->getOperand(0);
9123 Value *CmpRHS = ICI->getOperand(1);
9124 Value *TrueVal = SI.getTrueValue();
9125 Value *FalseVal = SI.getFalseValue();
9126
9127 // Check cases where the comparison is with a constant that
9128 // can be adjusted to fit the min/max idiom. We may edit ICI in
9129 // place here, so make sure the select is the only user.
9130 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009131 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009132 switch (Pred) {
9133 default: break;
9134 case ICmpInst::ICMP_ULT:
9135 case ICmpInst::ICMP_SLT: {
9136 // X < MIN ? T : F --> F
9137 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9138 return ReplaceInstUsesWith(SI, FalseVal);
9139 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009140 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009141 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9142 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9143 Pred = ICmpInst::getSwappedPredicate(Pred);
9144 CmpRHS = AdjustedRHS;
9145 std::swap(FalseVal, TrueVal);
9146 ICI->setPredicate(Pred);
9147 ICI->setOperand(1, CmpRHS);
9148 SI.setOperand(1, TrueVal);
9149 SI.setOperand(2, FalseVal);
9150 Changed = true;
9151 }
9152 break;
9153 }
9154 case ICmpInst::ICMP_UGT:
9155 case ICmpInst::ICMP_SGT: {
9156 // X > MAX ? T : F --> F
9157 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9158 return ReplaceInstUsesWith(SI, FalseVal);
9159 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009160 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009161 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9162 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9163 Pred = ICmpInst::getSwappedPredicate(Pred);
9164 CmpRHS = AdjustedRHS;
9165 std::swap(FalseVal, TrueVal);
9166 ICI->setPredicate(Pred);
9167 ICI->setOperand(1, CmpRHS);
9168 SI.setOperand(1, TrueVal);
9169 SI.setOperand(2, FalseVal);
9170 Changed = true;
9171 }
9172 break;
9173 }
9174 }
9175
Dan Gohman1975d032008-10-30 20:40:10 +00009176 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9177 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009178 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009179 if (match(TrueVal, m_ConstantInt<-1>()) &&
9180 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009181 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009182 else if (match(TrueVal, m_ConstantInt<0>()) &&
9183 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009184 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9185
Dan Gohman1975d032008-10-30 20:40:10 +00009186 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9187 // If we are just checking for a icmp eq of a single bit and zext'ing it
9188 // to an integer, then shift the bit to the appropriate place and then
9189 // cast to integer to avoid the comparison.
9190 const APInt &Op1CV = CI->getValue();
9191
9192 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9193 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9194 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009195 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009196 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009197 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009198 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009199 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009200 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009201 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009202 if (In->getType() != SI.getType())
9203 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009204 true/*SExt*/, "tmp", ICI);
9205
9206 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009207 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009208 In->getName()+".not"), *ICI);
9209
9210 return ReplaceInstUsesWith(SI, In);
9211 }
9212 }
9213 }
9214
Dan Gohman81b28ce2008-09-16 18:46:06 +00009215 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9216 // Transform (X == Y) ? X : Y -> Y
9217 if (Pred == ICmpInst::ICMP_EQ)
9218 return ReplaceInstUsesWith(SI, FalseVal);
9219 // Transform (X != Y) ? X : Y -> X
9220 if (Pred == ICmpInst::ICMP_NE)
9221 return ReplaceInstUsesWith(SI, TrueVal);
9222 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9223
9224 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9225 // Transform (X == Y) ? Y : X -> X
9226 if (Pred == ICmpInst::ICMP_EQ)
9227 return ReplaceInstUsesWith(SI, FalseVal);
9228 // Transform (X != Y) ? Y : X -> Y
9229 if (Pred == ICmpInst::ICMP_NE)
9230 return ReplaceInstUsesWith(SI, TrueVal);
9231 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9232 }
9233
9234 /// NOTE: if we wanted to, this is where to detect integer ABS
9235
9236 return Changed ? &SI : 0;
9237}
9238
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009239/// isDefinedInBB - Return true if the value is an instruction defined in the
9240/// specified basicblock.
9241static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9242 const Instruction *I = dyn_cast<Instruction>(V);
9243 return I != 0 && I->getParent() == BB;
9244}
9245
9246
Chris Lattner3d69f462004-03-12 05:52:32 +00009247Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009248 Value *CondVal = SI.getCondition();
9249 Value *TrueVal = SI.getTrueValue();
9250 Value *FalseVal = SI.getFalseValue();
9251
9252 // select true, X, Y -> X
9253 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009254 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009255 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009256
9257 // select C, X, X -> X
9258 if (TrueVal == FalseVal)
9259 return ReplaceInstUsesWith(SI, TrueVal);
9260
Chris Lattnere87597f2004-10-16 18:11:37 +00009261 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9262 return ReplaceInstUsesWith(SI, FalseVal);
9263 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9264 return ReplaceInstUsesWith(SI, TrueVal);
9265 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9266 if (isa<Constant>(TrueVal))
9267 return ReplaceInstUsesWith(SI, TrueVal);
9268 else
9269 return ReplaceInstUsesWith(SI, FalseVal);
9270 }
9271
Owen Anderson1d0be152009-08-13 21:58:54 +00009272 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009273 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009274 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009275 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009276 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009277 } else {
9278 // Change: A = select B, false, C --> A = and !B, C
9279 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009280 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009281 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009282 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009283 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009284 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009285 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009286 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009287 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009288 } else {
9289 // Change: A = select B, C, true --> A = or !B, C
9290 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009291 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009292 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009293 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009294 }
9295 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009296
9297 // select a, b, a -> a&b
9298 // select a, a, b -> a|b
9299 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009300 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009301 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009302 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009303 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009304
Chris Lattner2eefe512004-04-09 19:05:30 +00009305 // Selecting between two integer constants?
9306 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9307 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009308 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009309 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009310 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009311 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009312 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009313 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009314 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009315 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009316 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009317 }
Chris Lattner457dd822004-06-09 07:59:58 +00009318
Reid Spencere4d87aa2006-12-23 06:05:41 +00009319 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009320 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009321 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009322 // non-constant value, eliminate this whole mess. This corresponds to
9323 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009324 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009325 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009326 cast<Constant>(IC->getOperand(1))->isNullValue())
9327 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9328 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009329 isa<ConstantInt>(ICA->getOperand(1)) &&
9330 (ICA->getOperand(1) == TrueValC ||
9331 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009332 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9333 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009334 // know whether we have a icmp_ne or icmp_eq and whether the
9335 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009336 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009337 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009338 Value *V = ICA;
9339 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009340 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009341 Instruction::Xor, V, ICA->getOperand(1)), SI);
9342 return ReplaceInstUsesWith(SI, V);
9343 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009344 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009345 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009346
9347 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009348 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9349 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009350 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009351 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9352 // This is not safe in general for floating point:
9353 // consider X== -0, Y== +0.
9354 // It becomes safe if either operand is a nonzero constant.
9355 ConstantFP *CFPt, *CFPf;
9356 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9357 !CFPt->getValueAPF().isZero()) ||
9358 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9359 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009360 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009361 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009362 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009363 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009364 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009365 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009366
Reid Spencere4d87aa2006-12-23 06:05:41 +00009367 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009368 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009369 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9370 // This is not safe in general for floating point:
9371 // consider X== -0, Y== +0.
9372 // It becomes safe if either operand is a nonzero constant.
9373 ConstantFP *CFPt, *CFPf;
9374 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9375 !CFPt->getValueAPF().isZero()) ||
9376 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9377 !CFPf->getValueAPF().isZero()))
9378 return ReplaceInstUsesWith(SI, FalseVal);
9379 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009380 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009381 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9382 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009383 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009384 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009385 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009386 }
9387
9388 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009389 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9390 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9391 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009392
Chris Lattner87875da2005-01-13 22:52:24 +00009393 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9394 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9395 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009396 Instruction *AddOp = 0, *SubOp = 0;
9397
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009398 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9399 if (TI->getOpcode() == FI->getOpcode())
9400 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9401 return IV;
9402
9403 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9404 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009405 if ((TI->getOpcode() == Instruction::Sub &&
9406 FI->getOpcode() == Instruction::Add) ||
9407 (TI->getOpcode() == Instruction::FSub &&
9408 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009409 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009410 } else if ((FI->getOpcode() == Instruction::Sub &&
9411 TI->getOpcode() == Instruction::Add) ||
9412 (FI->getOpcode() == Instruction::FSub &&
9413 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009414 AddOp = TI; SubOp = FI;
9415 }
9416
9417 if (AddOp) {
9418 Value *OtherAddOp = 0;
9419 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9420 OtherAddOp = AddOp->getOperand(1);
9421 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9422 OtherAddOp = AddOp->getOperand(0);
9423 }
9424
9425 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009426 // So at this point we know we have (Y -> OtherAddOp):
9427 // select C, (add X, Y), (sub X, Z)
9428 Value *NegVal; // Compute -Z
9429 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009430 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009431 } else {
9432 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009433 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009434 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009435 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009436
9437 Value *NewTrueOp = OtherAddOp;
9438 Value *NewFalseOp = NegVal;
9439 if (AddOp != TI)
9440 std::swap(NewTrueOp, NewFalseOp);
9441 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009442 SelectInst::Create(CondVal, NewTrueOp,
9443 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009444
9445 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009446 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009447 }
9448 }
9449 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009450
Chris Lattnere576b912004-04-09 23:46:01 +00009451 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009452 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009453 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9454 if (FoldI)
9455 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009456 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009457
Chris Lattner5d1704d2009-09-27 19:57:57 +00009458 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009459 // to be live in the predecessor blocks. If they are instructions in SI's
9460 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009461 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009462 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9463 isa<PHINode>(SI.getTrueValue())) &&
9464 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9465 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009466 if (Instruction *NV = FoldOpIntoPhi(SI))
9467 return NV;
9468
Chris Lattnera1df33c2005-04-24 07:30:14 +00009469 if (BinaryOperator::isNot(CondVal)) {
9470 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9471 SI.setOperand(1, FalseVal);
9472 SI.setOperand(2, TrueVal);
9473 return &SI;
9474 }
9475
Chris Lattner3d69f462004-03-12 05:52:32 +00009476 return 0;
9477}
9478
Dan Gohmaneee962e2008-04-10 18:43:06 +00009479/// EnforceKnownAlignment - If the specified pointer points to an object that
9480/// we control, modify the object's alignment to PrefAlign. This isn't
9481/// often possible though. If alignment is important, a more reliable approach
9482/// is to simply align all global variables and allocation instructions to
9483/// their preferred alignment from the beginning.
9484///
9485static unsigned EnforceKnownAlignment(Value *V,
9486 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009487
Dan Gohmaneee962e2008-04-10 18:43:06 +00009488 User *U = dyn_cast<User>(V);
9489 if (!U) return Align;
9490
Dan Gohmanca178902009-07-17 20:47:02 +00009491 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009492 default: break;
9493 case Instruction::BitCast:
9494 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9495 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009496 // If all indexes are zero, it is just the alignment of the base pointer.
9497 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009498 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009499 if (!isa<Constant>(*i) ||
9500 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009501 AllZeroOperands = false;
9502 break;
9503 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009504
9505 if (AllZeroOperands) {
9506 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009507 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009508 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009509 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009510 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009511 }
9512
9513 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9514 // If there is a large requested alignment and we can, bump up the alignment
9515 // of the global.
9516 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009517 if (GV->getAlignment() >= PrefAlign)
9518 Align = GV->getAlignment();
9519 else {
9520 GV->setAlignment(PrefAlign);
9521 Align = PrefAlign;
9522 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009523 }
9524 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9525 // If there is a requested alignment and if this is an alloca, round up. We
9526 // don't do this for malloc, because some systems can't respect the request.
9527 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009528 if (AI->getAlignment() >= PrefAlign)
9529 Align = AI->getAlignment();
9530 else {
9531 AI->setAlignment(PrefAlign);
9532 Align = PrefAlign;
9533 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009534 }
Victor Hernandez83d63912009-09-18 22:35:49 +00009535 // No alignment changes are possible for malloc calls
Dan Gohmaneee962e2008-04-10 18:43:06 +00009536 }
9537
9538 return Align;
9539}
9540
9541/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9542/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9543/// and it is more than the alignment of the ultimate object, see if we can
9544/// increase the alignment of the ultimate object, making this check succeed.
9545unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9546 unsigned PrefAlign) {
9547 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9548 sizeof(PrefAlign) * CHAR_BIT;
9549 APInt Mask = APInt::getAllOnesValue(BitWidth);
9550 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9551 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9552 unsigned TrailZ = KnownZero.countTrailingOnes();
9553 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9554
9555 if (PrefAlign > Align)
9556 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9557
9558 // We don't need to make any adjustment.
9559 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009560}
9561
Chris Lattnerf497b022008-01-13 23:50:23 +00009562Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009563 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009564 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009565 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009566 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009567
9568 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009569 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009570 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009571 return MI;
9572 }
9573
9574 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9575 // load/store.
9576 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9577 if (MemOpLength == 0) return 0;
9578
Chris Lattner37ac6082008-01-14 00:28:35 +00009579 // Source and destination pointer types are always "i8*" for intrinsic. See
9580 // if the size is something we can handle with a single primitive load/store.
9581 // A single load+store correctly handles overlapping memory in the memmove
9582 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009583 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009584 if (Size == 0) return MI; // Delete this mem transfer.
9585
9586 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009587 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009588
Chris Lattner37ac6082008-01-14 00:28:35 +00009589 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009590 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009591 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009592
9593 // Memcpy forces the use of i8* for the source and destination. That means
9594 // that if you're using memcpy to move one double around, you'll get a cast
9595 // from double* to i8*. We'd much rather use a double load+store rather than
9596 // an i64 load+store, here because this improves the odds that the source or
9597 // dest address will be promotable. See if we can find a better type than the
9598 // integer datatype.
9599 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9600 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009601 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009602 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9603 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009604 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009605 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9606 if (STy->getNumElements() == 1)
9607 SrcETy = STy->getElementType(0);
9608 else
9609 break;
9610 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9611 if (ATy->getNumElements() == 1)
9612 SrcETy = ATy->getElementType();
9613 else
9614 break;
9615 } else
9616 break;
9617 }
9618
Dan Gohman8f8e2692008-05-23 01:52:21 +00009619 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009620 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009621 }
9622 }
9623
9624
Chris Lattnerf497b022008-01-13 23:50:23 +00009625 // If the memcpy/memmove provides better alignment info than we can
9626 // infer, use it.
9627 SrcAlign = std::max(SrcAlign, CopyAlign);
9628 DstAlign = std::max(DstAlign, CopyAlign);
9629
Chris Lattner08142f22009-08-30 19:47:22 +00009630 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9631 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009632 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9633 InsertNewInstBefore(L, *MI);
9634 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9635
9636 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009637 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009638 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009639}
Chris Lattner3d69f462004-03-12 05:52:32 +00009640
Chris Lattner69ea9d22008-04-30 06:39:11 +00009641Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9642 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009643 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009644 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009645 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009646 return MI;
9647 }
9648
9649 // Extract the length and alignment and fill if they are constant.
9650 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9651 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009652 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009653 return 0;
9654 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009655 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009656
9657 // If the length is zero, this is a no-op
9658 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9659
9660 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9661 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009662 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009663
9664 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009665 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009666
9667 // Alignment 0 is identity for alignment 1 for memset, but not store.
9668 if (Alignment == 0) Alignment = 1;
9669
9670 // Extract the fill value and store.
9671 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009672 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009673 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009674
9675 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009676 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009677 return MI;
9678 }
9679
9680 return 0;
9681}
9682
9683
Chris Lattner8b0ea312006-01-13 20:11:04 +00009684/// visitCallInst - CallInst simplification. This mostly only handles folding
9685/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9686/// the heavy lifting.
9687///
Chris Lattner9fe38862003-06-19 17:00:31 +00009688Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009689 // If the caller function is nounwind, mark the call as nounwind, even if the
9690 // callee isn't.
9691 if (CI.getParent()->getParent()->doesNotThrow() &&
9692 !CI.doesNotThrow()) {
9693 CI.setDoesNotThrow();
9694 return &CI;
9695 }
9696
Chris Lattner8b0ea312006-01-13 20:11:04 +00009697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9698 if (!II) return visitCallSite(&CI);
9699
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009700 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9701 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009702 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009703 bool Changed = false;
9704
9705 // memmove/cpy/set of zero bytes is a noop.
9706 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9707 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9708
Chris Lattner35b9e482004-10-12 04:52:52 +00009709 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009710 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009711 // Replace the instruction with just byte operations. We would
9712 // transform other cases to loads/stores, but we don't know if
9713 // alignment is sufficient.
9714 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009715 }
9716
Chris Lattner35b9e482004-10-12 04:52:52 +00009717 // If we have a memmove and the source operation is a constant global,
9718 // then the source and dest pointers can't alias, so we can change this
9719 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009720 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009721 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9722 if (GVSrc->isConstant()) {
9723 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009724 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9725 const Type *Tys[1];
9726 Tys[0] = CI.getOperand(3)->getType();
9727 CI.setOperand(0,
9728 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009729 Changed = true;
9730 }
Chris Lattnera935db82008-05-28 05:30:41 +00009731
9732 // memmove(x,x,size) -> noop.
9733 if (MMI->getSource() == MMI->getDest())
9734 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009735 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009736
Chris Lattner95a959d2006-03-06 20:18:44 +00009737 // If we can determine a pointer alignment that is bigger than currently
9738 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009739 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009740 if (Instruction *I = SimplifyMemTransfer(MI))
9741 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009742 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9743 if (Instruction *I = SimplifyMemSet(MSI))
9744 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009745 }
9746
Chris Lattner8b0ea312006-01-13 20:11:04 +00009747 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009748 }
9749
9750 switch (II->getIntrinsicID()) {
9751 default: break;
9752 case Intrinsic::bswap:
9753 // bswap(bswap(x)) -> x
9754 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9755 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9756 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9757 break;
9758 case Intrinsic::ppc_altivec_lvx:
9759 case Intrinsic::ppc_altivec_lvxl:
9760 case Intrinsic::x86_sse_loadu_ps:
9761 case Intrinsic::x86_sse2_loadu_pd:
9762 case Intrinsic::x86_sse2_loadu_dq:
9763 // Turn PPC lvx -> load if the pointer is known aligned.
9764 // Turn X86 loadups -> load if the pointer is known aligned.
9765 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009766 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9767 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009768 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009769 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009770 break;
9771 case Intrinsic::ppc_altivec_stvx:
9772 case Intrinsic::ppc_altivec_stvxl:
9773 // Turn stvx -> store if the pointer is known aligned.
9774 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9775 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009776 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009777 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009778 return new StoreInst(II->getOperand(1), Ptr);
9779 }
9780 break;
9781 case Intrinsic::x86_sse_storeu_ps:
9782 case Intrinsic::x86_sse2_storeu_pd:
9783 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009784 // Turn X86 storeu -> store if the pointer is known aligned.
9785 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9786 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009787 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009788 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009789 return new StoreInst(II->getOperand(2), Ptr);
9790 }
9791 break;
9792
9793 case Intrinsic::x86_sse_cvttss2si: {
9794 // These intrinsics only demands the 0th element of its input vector. If
9795 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009796 unsigned VWidth =
9797 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9798 APInt DemandedElts(VWidth, 1);
9799 APInt UndefElts(VWidth, 0);
9800 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009801 UndefElts)) {
9802 II->setOperand(1, V);
9803 return II;
9804 }
9805 break;
9806 }
9807
9808 case Intrinsic::ppc_altivec_vperm:
9809 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9810 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9811 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009812
Chris Lattner0521e3c2008-06-18 04:33:20 +00009813 // Check that all of the elements are integer constants or undefs.
9814 bool AllEltsOk = true;
9815 for (unsigned i = 0; i != 16; ++i) {
9816 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9817 !isa<UndefValue>(Mask->getOperand(i))) {
9818 AllEltsOk = false;
9819 break;
9820 }
9821 }
9822
9823 if (AllEltsOk) {
9824 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009825 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9826 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009827 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009828
Chris Lattner0521e3c2008-06-18 04:33:20 +00009829 // Only extract each element once.
9830 Value *ExtractedElts[32];
9831 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9832
Chris Lattnere2ed0572006-04-06 19:19:17 +00009833 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009834 if (isa<UndefValue>(Mask->getOperand(i)))
9835 continue;
9836 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9837 Idx &= 31; // Match the hardware behavior.
9838
9839 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009840 ExtractedElts[Idx] =
9841 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9842 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9843 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009844 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009845
Chris Lattner0521e3c2008-06-18 04:33:20 +00009846 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009847 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9848 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9849 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009850 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009851 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009852 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009853 }
9854 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009855
Chris Lattner0521e3c2008-06-18 04:33:20 +00009856 case Intrinsic::stackrestore: {
9857 // If the save is right next to the restore, remove the restore. This can
9858 // happen when variable allocas are DCE'd.
9859 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9860 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9861 BasicBlock::iterator BI = SS;
9862 if (&*++BI == II)
9863 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009864 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009865 }
9866
9867 // Scan down this block to see if there is another stack restore in the
9868 // same block without an intervening call/alloca.
9869 BasicBlock::iterator BI = II;
9870 TerminatorInst *TI = II->getParent()->getTerminator();
9871 bool CannotRemove = false;
9872 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009873 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009874 CannotRemove = true;
9875 break;
9876 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009877 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9878 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9879 // If there is a stackrestore below this one, remove this one.
9880 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9881 return EraseInstFromFunction(CI);
9882 // Otherwise, ignore the intrinsic.
9883 } else {
9884 // If we found a non-intrinsic call, we can't remove the stack
9885 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009886 CannotRemove = true;
9887 break;
9888 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009889 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009890 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009891
9892 // If the stack restore is in a return/unwind block and if there are no
9893 // allocas or calls between the restore and the return, nuke the restore.
9894 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9895 return EraseInstFromFunction(CI);
9896 break;
9897 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009898 }
9899
Chris Lattner8b0ea312006-01-13 20:11:04 +00009900 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009901}
9902
9903// InvokeInst simplification
9904//
9905Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009906 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009907}
9908
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009909/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9910/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009911static bool isSafeToEliminateVarargsCast(const CallSite CS,
9912 const CastInst * const CI,
9913 const TargetData * const TD,
9914 const int ix) {
9915 if (!CI->isLosslessCast())
9916 return false;
9917
9918 // The size of ByVal arguments is derived from the type, so we
9919 // can't change to a type with a different size. If the size were
9920 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009921 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009922 return true;
9923
9924 const Type* SrcTy =
9925 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9926 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9927 if (!SrcTy->isSized() || !DstTy->isSized())
9928 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009929 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009930 return false;
9931 return true;
9932}
9933
Chris Lattnera44d8a22003-10-07 22:32:43 +00009934// visitCallSite - Improvements for call and invoke instructions.
9935//
9936Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009937 bool Changed = false;
9938
9939 // If the callee is a constexpr cast of a function, attempt to move the cast
9940 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009941 if (transformConstExprCastCall(CS)) return 0;
9942
Chris Lattner6c266db2003-10-07 22:54:13 +00009943 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009944
Chris Lattner08b22ec2005-05-13 07:09:09 +00009945 if (Function *CalleeF = dyn_cast<Function>(Callee))
9946 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9947 Instruction *OldCall = CS.getInstruction();
9948 // If the call and callee calling conventions don't match, this call must
9949 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009950 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009951 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009952 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009953 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009954 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009955 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9956 return EraseInstFromFunction(*OldCall);
9957 return 0;
9958 }
9959
Chris Lattner17be6352004-10-18 02:59:09 +00009960 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9961 // This instruction is not reachable, just remove it. We insert a store to
9962 // undef so that we know that this code is not reachable, despite the fact
9963 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009964 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009965 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009966 CS.getInstruction());
9967
9968 if (!CS.getInstruction()->use_empty())
9969 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009970 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009971
9972 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9973 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009974 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009975 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009976 }
Chris Lattner17be6352004-10-18 02:59:09 +00009977 return EraseInstFromFunction(*CS.getInstruction());
9978 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009979
Duncan Sandscdb6d922007-09-17 10:26:40 +00009980 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9981 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9982 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9983 return transformCallThroughTrampoline(CS);
9984
Chris Lattner6c266db2003-10-07 22:54:13 +00009985 const PointerType *PTy = cast<PointerType>(Callee->getType());
9986 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9987 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009988 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009989 // See if we can optimize any arguments passed through the varargs area of
9990 // the call.
9991 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009992 E = CS.arg_end(); I != E; ++I, ++ix) {
9993 CastInst *CI = dyn_cast<CastInst>(*I);
9994 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9995 *I = CI->getOperand(0);
9996 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009997 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009998 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009999 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010000
Duncan Sandsf0c33542007-12-19 21:13:37 +000010001 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010002 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010003 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010004 Changed = true;
10005 }
10006
Chris Lattner6c266db2003-10-07 22:54:13 +000010007 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010008}
10009
Chris Lattner9fe38862003-06-19 17:00:31 +000010010// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10011// attempt to move the cast to the arguments of the call/invoke.
10012//
10013bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10014 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10015 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010016 if (CE->getOpcode() != Instruction::BitCast ||
10017 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010018 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010019 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010020 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010021 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010022
10023 // Okay, this is a cast from a function to a different type. Unless doing so
10024 // would cause a type conversion of one of our arguments, change this call to
10025 // be a direct call with arguments casted to the appropriate types.
10026 //
10027 const FunctionType *FT = Callee->getFunctionType();
10028 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010029 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010030
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010031 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010032 return false; // TODO: Handle multiple return values.
10033
Chris Lattnerf78616b2004-01-14 06:06:08 +000010034 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010035 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010036 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010037 // Conversion is ok if changing from one pointer type to another or from
10038 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010039 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010040 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010041 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010042 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010043 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010044
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010045 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010046 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010047 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010048 return false; // Cannot transform this return value.
10049
Chris Lattner58d74912008-03-12 17:45:29 +000010050 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010051 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010052 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010053 return false; // Attribute not compatible with transformed value.
10054 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010055
Chris Lattnerf78616b2004-01-14 06:06:08 +000010056 // If the callsite is an invoke instruction, and the return value is used by
10057 // a PHI node in a successor, we cannot change the return type of the call
10058 // because there is no place to put the cast instruction (without breaking
10059 // the critical edge). Bail out in this case.
10060 if (!Caller->use_empty())
10061 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10062 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10063 UI != E; ++UI)
10064 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10065 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010066 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010067 return false;
10068 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010069
10070 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10071 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010072
Chris Lattner9fe38862003-06-19 17:00:31 +000010073 CallSite::arg_iterator AI = CS.arg_begin();
10074 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10075 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010076 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010077
10078 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010079 return false; // Cannot transform this parameter value.
10080
Devang Patel19c87462008-09-26 22:53:05 +000010081 if (CallerPAL.getParamAttributes(i + 1)
10082 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010083 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010084
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010085 // Converting from one pointer type to another or between a pointer and an
10086 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010087 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010088 (TD && ((isa<PointerType>(ParamTy) ||
10089 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10090 (isa<PointerType>(ActTy) ||
10091 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010092 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010093 }
10094
10095 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010096 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010097 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010098
Chris Lattner58d74912008-03-12 17:45:29 +000010099 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10100 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010101 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010102 // won't be dropping them. Check that these extra arguments have attributes
10103 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010104 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10105 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010106 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010107 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010108 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010109 return false;
10110 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010111
Chris Lattner9fe38862003-06-19 17:00:31 +000010112 // Okay, we decided that this is a safe thing to do: go ahead and start
10113 // inserting cast instructions as necessary...
10114 std::vector<Value*> Args;
10115 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010116 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010117 attrVec.reserve(NumCommonArgs);
10118
10119 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010120 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010121
10122 // If the return value is not being used, the type may not be compatible
10123 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010124 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010125
10126 // Add the new return attributes.
10127 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010128 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010129
10130 AI = CS.arg_begin();
10131 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10132 const Type *ParamTy = FT->getParamType(i);
10133 if ((*AI)->getType() == ParamTy) {
10134 Args.push_back(*AI);
10135 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010136 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010137 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010138 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010139 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010140
10141 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010142 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010143 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010144 }
10145
10146 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010147 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010148 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010149 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010150
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010151 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010152 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010153 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010154 errs() << "WARNING: While resolving call to function '"
10155 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010156 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010157 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010158 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10159 const Type *PTy = getPromotedType((*AI)->getType());
10160 if (PTy != (*AI)->getType()) {
10161 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010162 Instruction::CastOps opcode =
10163 CastInst::getCastOpcode(*AI, false, PTy, false);
10164 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010165 } else {
10166 Args.push_back(*AI);
10167 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010168
Duncan Sandse1e520f2008-01-13 08:02:44 +000010169 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010170 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010171 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010172 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010173 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010174 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010175
Devang Patel19c87462008-09-26 22:53:05 +000010176 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10177 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10178
Owen Anderson1d0be152009-08-13 21:58:54 +000010179 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010180 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010181
Eric Christophera66297a2009-07-25 02:45:27 +000010182 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10183 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010184
Chris Lattner9fe38862003-06-19 17:00:31 +000010185 Instruction *NC;
10186 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010187 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010188 Args.begin(), Args.end(),
10189 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010190 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010191 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010192 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010193 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10194 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010195 CallInst *CI = cast<CallInst>(Caller);
10196 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010197 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010198 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010199 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010200 }
10201
Chris Lattner6934a042007-02-11 01:23:03 +000010202 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010203 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010204 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010205 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010206 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010207 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010208 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010209
10210 // If this is an invoke instruction, we should insert it after the first
10211 // non-phi, instruction in the normal successor block.
10212 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010213 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010214 InsertNewInstBefore(NC, *I);
10215 } else {
10216 // Otherwise, it's a call, just insert cast right after the call instr
10217 InsertNewInstBefore(NC, *Caller);
10218 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010219 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010220 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010221 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010222 }
10223 }
10224
Chris Lattner931f8f32009-08-31 05:17:58 +000010225
10226 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010227 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010228
10229 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010230 return true;
10231}
10232
Duncan Sandscdb6d922007-09-17 10:26:40 +000010233// transformCallThroughTrampoline - Turn a call to a function created by the
10234// init_trampoline intrinsic into a direct call to the underlying function.
10235//
10236Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10237 Value *Callee = CS.getCalledValue();
10238 const PointerType *PTy = cast<PointerType>(Callee->getType());
10239 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010240 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010241
10242 // If the call already has the 'nest' attribute somewhere then give up -
10243 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010244 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010245 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246
10247 IntrinsicInst *Tramp =
10248 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10249
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010250 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010251 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10252 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10253
Devang Patel05988662008-09-25 21:00:45 +000010254 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010255 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010256 unsigned NestIdx = 1;
10257 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010258 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010259
10260 // Look for a parameter marked with the 'nest' attribute.
10261 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10262 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010263 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010264 // Record the parameter type and any other attributes.
10265 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010266 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010267 break;
10268 }
10269
10270 if (NestTy) {
10271 Instruction *Caller = CS.getInstruction();
10272 std::vector<Value*> NewArgs;
10273 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10274
Devang Patel05988662008-09-25 21:00:45 +000010275 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010276 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010277
Duncan Sandscdb6d922007-09-17 10:26:40 +000010278 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010279 // mean appending it. Likewise for attributes.
10280
Devang Patel19c87462008-09-26 22:53:05 +000010281 // Add any result attributes.
10282 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010283 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010284
Duncan Sandscdb6d922007-09-17 10:26:40 +000010285 {
10286 unsigned Idx = 1;
10287 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10288 do {
10289 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010290 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010291 Value *NestVal = Tramp->getOperand(3);
10292 if (NestVal->getType() != NestTy)
10293 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10294 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010295 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010296 }
10297
10298 if (I == E)
10299 break;
10300
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010301 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010302 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010303 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010304 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010305 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010306
10307 ++Idx, ++I;
10308 } while (1);
10309 }
10310
Devang Patel19c87462008-09-26 22:53:05 +000010311 // Add any function attributes.
10312 if (Attributes Attr = Attrs.getFnAttributes())
10313 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10314
Duncan Sandscdb6d922007-09-17 10:26:40 +000010315 // The trampoline may have been bitcast to a bogus type (FTy).
10316 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010317 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010318
Duncan Sandscdb6d922007-09-17 10:26:40 +000010319 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010320 NewTypes.reserve(FTy->getNumParams()+1);
10321
Duncan Sandscdb6d922007-09-17 10:26:40 +000010322 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010323 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010324 {
10325 unsigned Idx = 1;
10326 FunctionType::param_iterator I = FTy->param_begin(),
10327 E = FTy->param_end();
10328
10329 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010330 if (Idx == NestIdx)
10331 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010332 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010333
10334 if (I == E)
10335 break;
10336
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010337 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010339
10340 ++Idx, ++I;
10341 } while (1);
10342 }
10343
10344 // Replace the trampoline call with a direct call. Let the generic
10345 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010346 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010347 FTy->isVarArg());
10348 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010349 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010350 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010351 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010352 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10353 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010354
10355 Instruction *NewCaller;
10356 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010357 NewCaller = InvokeInst::Create(NewCallee,
10358 II->getNormalDest(), II->getUnwindDest(),
10359 NewArgs.begin(), NewArgs.end(),
10360 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010361 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010362 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010363 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010364 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10365 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366 if (cast<CallInst>(Caller)->isTailCall())
10367 cast<CallInst>(NewCaller)->setTailCall();
10368 cast<CallInst>(NewCaller)->
10369 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010370 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010371 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010372 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010373 Caller->replaceAllUsesWith(NewCaller);
10374 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010375 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 return 0;
10377 }
10378 }
10379
10380 // Replace the trampoline call with a direct call. Since there is no 'nest'
10381 // parameter, there is no need to adjust the argument list. Let the generic
10382 // code sort out any function type mismatches.
10383 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010384 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010385 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010386 CS.setCalledFunction(NewCallee);
10387 return CS.getInstruction();
10388}
10389
Dan Gohman9ad29202009-09-16 16:50:24 +000010390/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10391/// 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 +000010392/// and a single binop.
10393Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10394 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010395 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010396 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010397 Value *LHSVal = FirstInst->getOperand(0);
10398 Value *RHSVal = FirstInst->getOperand(1);
10399
10400 const Type *LHSType = LHSVal->getType();
10401 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010402
Dan Gohman9ad29202009-09-16 16:50:24 +000010403 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010404 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010405 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010406 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010407 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010408 // types or GEP's with different index types.
10409 I->getOperand(0)->getType() != LHSType ||
10410 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010411 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010412
10413 // If they are CmpInst instructions, check their predicates
10414 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10415 if (cast<CmpInst>(I)->getPredicate() !=
10416 cast<CmpInst>(FirstInst)->getPredicate())
10417 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010418
10419 // Keep track of which operand needs a phi node.
10420 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10421 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010422 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010423
10424 // If both LHS and RHS would need a PHI, don't do this transformation,
10425 // because it would increase the number of PHIs entering the block,
10426 // which leads to higher register pressure. This is especially
10427 // bad when the PHIs are in the header of a loop.
10428 if (!LHSVal && !RHSVal)
10429 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010430
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010431 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010432
Chris Lattner7da52b22006-11-01 04:51:18 +000010433 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010434 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010435 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010436 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010437 NewLHS = PHINode::Create(LHSType,
10438 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010439 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10440 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010441 InsertNewInstBefore(NewLHS, PN);
10442 LHSVal = NewLHS;
10443 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010444
10445 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010446 NewRHS = PHINode::Create(RHSType,
10447 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010448 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10449 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010450 InsertNewInstBefore(NewRHS, PN);
10451 RHSVal = NewRHS;
10452 }
10453
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010454 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010455 if (NewLHS || NewRHS) {
10456 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10457 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10458 if (NewLHS) {
10459 Value *NewInLHS = InInst->getOperand(0);
10460 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10461 }
10462 if (NewRHS) {
10463 Value *NewInRHS = InInst->getOperand(1);
10464 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10465 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010466 }
10467 }
10468
Chris Lattner7da52b22006-11-01 04:51:18 +000010469 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010470 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010471 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010472 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010473 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010474}
10475
Chris Lattner05f18922008-12-01 02:34:36 +000010476Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10477 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10478
10479 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10480 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010481 // This is true if all GEP bases are allocas and if all indices into them are
10482 // constants.
10483 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010484
10485 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010486 // more than one phi, which leads to higher register pressure. This is
10487 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010488 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010489
Dan Gohman9ad29202009-09-16 16:50:24 +000010490 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010491 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10492 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10493 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10494 GEP->getNumOperands() != FirstInst->getNumOperands())
10495 return 0;
10496
Chris Lattner36d3e322009-02-21 00:46:50 +000010497 // Keep track of whether or not all GEPs are of alloca pointers.
10498 if (AllBasePointersAreAllocas &&
10499 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10500 !GEP->hasAllConstantIndices()))
10501 AllBasePointersAreAllocas = false;
10502
Chris Lattner05f18922008-12-01 02:34:36 +000010503 // Compare the operand lists.
10504 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10505 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10506 continue;
10507
10508 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10509 // if one of the PHIs has a constant for the index. The index may be
10510 // substantially cheaper to compute for the constants, so making it a
10511 // variable index could pessimize the path. This also handles the case
10512 // for struct indices, which must always be constant.
10513 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10514 isa<ConstantInt>(GEP->getOperand(op)))
10515 return 0;
10516
10517 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10518 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010519
10520 // If we already needed a PHI for an earlier operand, and another operand
10521 // also requires a PHI, we'd be introducing more PHIs than we're
10522 // eliminating, which increases register pressure on entry to the PHI's
10523 // block.
10524 if (NeededPhi)
10525 return 0;
10526
Chris Lattner05f18922008-12-01 02:34:36 +000010527 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010528 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010529 }
10530 }
10531
Chris Lattner36d3e322009-02-21 00:46:50 +000010532 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010533 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010534 // offset calculation, but all the predecessors will have to materialize the
10535 // stack address into a register anyway. We'd actually rather *clone* the
10536 // load up into the predecessors so that we have a load of a gep of an alloca,
10537 // which can usually all be folded into the load.
10538 if (AllBasePointersAreAllocas)
10539 return 0;
10540
Chris Lattner05f18922008-12-01 02:34:36 +000010541 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10542 // that is variable.
10543 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10544
10545 bool HasAnyPHIs = false;
10546 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10547 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10548 Value *FirstOp = FirstInst->getOperand(i);
10549 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10550 FirstOp->getName()+".pn");
10551 InsertNewInstBefore(NewPN, PN);
10552
10553 NewPN->reserveOperandSpace(e);
10554 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10555 OperandPhis[i] = NewPN;
10556 FixedOperands[i] = NewPN;
10557 HasAnyPHIs = true;
10558 }
10559
10560
10561 // Add all operands to the new PHIs.
10562 if (HasAnyPHIs) {
10563 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10564 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10565 BasicBlock *InBB = PN.getIncomingBlock(i);
10566
10567 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10568 if (PHINode *OpPhi = OperandPhis[op])
10569 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10570 }
10571 }
10572
10573 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010574 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10575 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10576 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010577 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10578 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010579}
10580
10581
Chris Lattner21550882009-02-23 05:56:17 +000010582/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10583/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010584/// obvious the value of the load is not changed from the point of the load to
10585/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010586///
10587/// Finally, it is safe, but not profitable, to sink a load targetting a
10588/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10589/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010590static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010591 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10592
10593 for (++BBI; BBI != E; ++BBI)
10594 if (BBI->mayWriteToMemory())
10595 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010596
10597 // Check for non-address taken alloca. If not address-taken already, it isn't
10598 // profitable to do this xform.
10599 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10600 bool isAddressTaken = false;
10601 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10602 UI != E; ++UI) {
10603 if (isa<LoadInst>(UI)) continue;
10604 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10605 // If storing TO the alloca, then the address isn't taken.
10606 if (SI->getOperand(1) == AI) continue;
10607 }
10608 isAddressTaken = true;
10609 break;
10610 }
10611
Chris Lattner36d3e322009-02-21 00:46:50 +000010612 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010613 return false;
10614 }
10615
Chris Lattner36d3e322009-02-21 00:46:50 +000010616 // If this load is a load from a GEP with a constant offset from an alloca,
10617 // then we don't want to sink it. In its present form, it will be
10618 // load [constant stack offset]. Sinking it will cause us to have to
10619 // materialize the stack addresses in each predecessor in a register only to
10620 // do a shared load from register in the successor.
10621 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10622 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10623 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10624 return false;
10625
Chris Lattner76c73142006-11-01 07:13:54 +000010626 return true;
10627}
10628
Chris Lattner9fe38862003-06-19 17:00:31 +000010629
Chris Lattnerbac32862004-11-14 19:13:23 +000010630// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10631// operator and they all are only used by the PHI, PHI together their
10632// inputs, and do the operation once, to the result of the PHI.
10633Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10634 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10635
10636 // Scan the instruction, looking for input operations that can be folded away.
10637 // If all input operands to the phi are the same instruction (e.g. a cast from
10638 // the same type or "+42") we can pull the operation through the PHI, reducing
10639 // code size and simplifying code.
10640 Constant *ConstantOp = 0;
10641 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010642 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010643 if (isa<CastInst>(FirstInst)) {
10644 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010645 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010646 // Can fold binop, compare or shift here if the RHS is a constant,
10647 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010648 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010649 if (ConstantOp == 0)
10650 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010651 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10652 isVolatile = LI->isVolatile();
10653 // We can't sink the load if the loaded value could be modified between the
10654 // load and the PHI.
10655 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010656 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010657 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010658
10659 // If the PHI is of volatile loads and the load block has multiple
10660 // successors, sinking it would remove a load of the volatile value from
10661 // the path through the other successor.
10662 if (isVolatile &&
10663 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10664 return 0;
10665
Chris Lattner9c080502006-11-01 07:43:41 +000010666 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010667 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010668 } else {
10669 return 0; // Cannot fold this operation.
10670 }
10671
10672 // Check to see if all arguments are the same operation.
10673 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10674 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10675 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010676 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010677 return 0;
10678 if (CastSrcTy) {
10679 if (I->getOperand(0)->getType() != CastSrcTy)
10680 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010681 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010682 // We can't sink the load if the loaded value could be modified between
10683 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010684 if (LI->isVolatile() != isVolatile ||
10685 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010686 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010687 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010688
Chris Lattner71042962008-07-08 17:18:32 +000010689 // If the PHI is of volatile loads and the load block has multiple
10690 // successors, sinking it would remove a load of the volatile value from
10691 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010692 if (isVolatile &&
10693 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10694 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010695
Chris Lattnerbac32862004-11-14 19:13:23 +000010696 } else if (I->getOperand(1) != ConstantOp) {
10697 return 0;
10698 }
10699 }
10700
10701 // Okay, they are all the same operation. Create a new PHI node of the
10702 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010703 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10704 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010705 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010706
10707 Value *InVal = FirstInst->getOperand(0);
10708 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010709
10710 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010711 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10712 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10713 if (NewInVal != InVal)
10714 InVal = 0;
10715 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10716 }
10717
10718 Value *PhiVal;
10719 if (InVal) {
10720 // The new PHI unions all of the same values together. This is really
10721 // common, so we handle it intelligently here for compile-time speed.
10722 PhiVal = InVal;
10723 delete NewPN;
10724 } else {
10725 InsertNewInstBefore(NewPN, PN);
10726 PhiVal = NewPN;
10727 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010728
Chris Lattnerbac32862004-11-14 19:13:23 +000010729 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010730 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010731 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010732 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010733 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010734 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010735 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010736 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010737 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10738
10739 // If this was a volatile load that we are merging, make sure to loop through
10740 // and mark all the input loads as non-volatile. If we don't do this, we will
10741 // insert a new volatile load and the old ones will not be deletable.
10742 if (isVolatile)
10743 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10744 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10745
10746 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010747}
Chris Lattnera1be5662002-05-02 17:06:02 +000010748
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010749/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10750/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010751static bool DeadPHICycle(PHINode *PN,
10752 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010753 if (PN->use_empty()) return true;
10754 if (!PN->hasOneUse()) return false;
10755
10756 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010757 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010758 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010759
10760 // Don't scan crazily complex things.
10761 if (PotentiallyDeadPHIs.size() == 16)
10762 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010763
10764 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10765 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010766
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010767 return false;
10768}
10769
Chris Lattnercf5008a2007-11-06 21:52:06 +000010770/// PHIsEqualValue - Return true if this phi node is always equal to
10771/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10772/// z = some value; x = phi (y, z); y = phi (x, z)
10773static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10774 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10775 // See if we already saw this PHI node.
10776 if (!ValueEqualPHIs.insert(PN))
10777 return true;
10778
10779 // Don't scan crazily complex things.
10780 if (ValueEqualPHIs.size() == 16)
10781 return false;
10782
10783 // Scan the operands to see if they are either phi nodes or are equal to
10784 // the value.
10785 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10786 Value *Op = PN->getIncomingValue(i);
10787 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10788 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10789 return false;
10790 } else if (Op != NonPhiInVal)
10791 return false;
10792 }
10793
10794 return true;
10795}
10796
10797
Chris Lattner473945d2002-05-06 18:06:38 +000010798// PHINode simplification
10799//
Chris Lattner7e708292002-06-25 16:13:24 +000010800Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010801 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010802 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010803
Owen Anderson7e057142006-07-10 22:03:18 +000010804 if (Value *V = PN.hasConstantValue())
10805 return ReplaceInstUsesWith(PN, V);
10806
Owen Anderson7e057142006-07-10 22:03:18 +000010807 // If all PHI operands are the same operation, pull them through the PHI,
10808 // reducing code size.
10809 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010810 isa<Instruction>(PN.getIncomingValue(1)) &&
10811 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10812 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10813 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10814 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010815 PN.getIncomingValue(0)->hasOneUse())
10816 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10817 return Result;
10818
10819 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10820 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10821 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010822 if (PN.hasOneUse()) {
10823 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10824 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010825 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010826 PotentiallyDeadPHIs.insert(&PN);
10827 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010828 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010829 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010830
10831 // If this phi has a single use, and if that use just computes a value for
10832 // the next iteration of a loop, delete the phi. This occurs with unused
10833 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10834 // common case here is good because the only other things that catch this
10835 // are induction variable analysis (sometimes) and ADCE, which is only run
10836 // late.
10837 if (PHIUser->hasOneUse() &&
10838 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10839 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010840 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010841 }
10842 }
Owen Anderson7e057142006-07-10 22:03:18 +000010843
Chris Lattnercf5008a2007-11-06 21:52:06 +000010844 // We sometimes end up with phi cycles that non-obviously end up being the
10845 // same value, for example:
10846 // z = some value; x = phi (y, z); y = phi (x, z)
10847 // where the phi nodes don't necessarily need to be in the same block. Do a
10848 // quick check to see if the PHI node only contains a single non-phi value, if
10849 // so, scan to see if the phi cycle is actually equal to that value.
10850 {
10851 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10852 // Scan for the first non-phi operand.
10853 while (InValNo != NumOperandVals &&
10854 isa<PHINode>(PN.getIncomingValue(InValNo)))
10855 ++InValNo;
10856
10857 if (InValNo != NumOperandVals) {
10858 Value *NonPhiInVal = PN.getOperand(InValNo);
10859
10860 // Scan the rest of the operands to see if there are any conflicts, if so
10861 // there is no need to recursively scan other phis.
10862 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10863 Value *OpVal = PN.getIncomingValue(InValNo);
10864 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10865 break;
10866 }
10867
10868 // If we scanned over all operands, then we have one unique value plus
10869 // phi values. Scan PHI nodes to see if they all merge in each other or
10870 // the value.
10871 if (InValNo == NumOperandVals) {
10872 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10873 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10874 return ReplaceInstUsesWith(PN, NonPhiInVal);
10875 }
10876 }
10877 }
Chris Lattner60921c92003-12-19 05:58:40 +000010878 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010879}
10880
Chris Lattner7e708292002-06-25 16:13:24 +000010881Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010882 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010883 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010884 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010885 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010886
Chris Lattnere87597f2004-10-16 18:11:37 +000010887 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010888 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010889
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010890 bool HasZeroPointerIndex = false;
10891 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10892 HasZeroPointerIndex = C->isNullValue();
10893
10894 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010895 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010896
Chris Lattner28977af2004-04-05 01:30:19 +000010897 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010898 if (TD) {
10899 bool MadeChange = false;
10900 unsigned PtrSize = TD->getPointerSizeInBits();
10901
10902 gep_type_iterator GTI = gep_type_begin(GEP);
10903 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10904 I != E; ++I, ++GTI) {
10905 if (!isa<SequentialType>(*GTI)) continue;
10906
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010907 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010908 // to what we need. If narrower, sign-extend it to what we need. This
10909 // explicit cast can make subsequent optimizations more obvious.
10910 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010911 if (OpBits == PtrSize)
10912 continue;
10913
Chris Lattner2345d1d2009-08-30 20:01:10 +000010914 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010915 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010916 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010917 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010918 }
Chris Lattner28977af2004-04-05 01:30:19 +000010919
Chris Lattner90ac28c2002-08-02 19:29:35 +000010920 // Combine Indices - If the source pointer to this getelementptr instruction
10921 // is a getelementptr instruction, combine the indices of the two
10922 // getelementptr instructions into a single instruction.
10923 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010924 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010925 // Note that if our source is a gep chain itself that we wait for that
10926 // chain to be resolved before we perform this transformation. This
10927 // avoids us creating a TON of code in some cases.
10928 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010929 if (GetElementPtrInst *SrcGEP =
10930 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10931 if (SrcGEP->getNumOperands() == 2)
10932 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010933
Chris Lattner72588fc2007-02-15 22:48:32 +000010934 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010935
10936 // Find out whether the last index in the source GEP is a sequential idx.
10937 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010938 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10939 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010940 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010941
Chris Lattner90ac28c2002-08-02 19:29:35 +000010942 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010943 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010944 // Replace: gep (gep %P, long B), long A, ...
10945 // With: T = long A+B; gep %P, T, ...
10946 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010947 Value *Sum;
10948 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10949 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010950 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010951 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010952 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010953 Sum = SO1;
10954 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010955 // If they aren't the same type, then the input hasn't been processed
10956 // by the loop above yet (which canonicalizes sequential index types to
10957 // intptr_t). Just avoid transforming this until the input has been
10958 // normalized.
10959 if (SO1->getType() != GO1->getType())
10960 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010961 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010962 }
Chris Lattner620ce142004-05-07 22:09:22 +000010963
Chris Lattnerab984842009-08-30 05:30:55 +000010964 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010965 if (Src->getNumOperands() == 2) {
10966 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010967 GEP.setOperand(1, Sum);
10968 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010969 }
Chris Lattnerab984842009-08-30 05:30:55 +000010970 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010971 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010972 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010973 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010974 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010975 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010976 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010977 Indices.append(Src->op_begin()+1, Src->op_end());
10978 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010979 }
10980
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010981 if (!Indices.empty())
10982 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10983 Src->isInBounds()) ?
10984 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10985 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010986 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010987 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010988 }
10989
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010990 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10991 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010992 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010993
Chris Lattner2de23192009-08-30 20:38:21 +000010994 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10995 // want to change the gep until the bitcasts are eliminated.
10996 if (getBitCastOperand(X)) {
10997 Worklist.AddValue(PtrOp);
10998 return 0;
10999 }
11000
Chris Lattner963f4ba2009-08-30 20:36:46 +000011001 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11002 // into : GEP [10 x i8]* X, i32 0, ...
11003 //
11004 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11005 // into : GEP i8* X, ...
11006 //
11007 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011008 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011009 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11010 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011011 if (const ArrayType *CATy =
11012 dyn_cast<ArrayType>(CPTy->getElementType())) {
11013 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11014 if (CATy->getElementType() == XTy->getElementType()) {
11015 // -> GEP i8* X, ...
11016 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011017 return cast<GEPOperator>(&GEP)->isInBounds() ?
11018 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11019 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011020 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11021 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011022 }
11023
11024 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011025 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011026 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011027 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011028 // At this point, we know that the cast source type is a pointer
11029 // to an array of the same type as the destination pointer
11030 // array. Because the array type is never stepped over (there
11031 // is a leading zero) we can fold the cast into this GEP.
11032 GEP.setOperand(0, X);
11033 return &GEP;
11034 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011035 }
11036 }
Chris Lattnereed48272005-09-13 00:40:14 +000011037 } else if (GEP.getNumOperands() == 2) {
11038 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011039 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11040 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011041 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11042 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011043 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011044 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11045 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011046 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011047 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011048 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011049 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11050 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011051 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011052 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011053 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011054 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011055
11056 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011057 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011058 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011059 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011060
Owen Anderson1d0be152009-08-13 21:58:54 +000011061 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011062 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011063 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011064
11065 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11066 // allow either a mul, shift, or constant here.
11067 Value *NewIdx = 0;
11068 ConstantInt *Scale = 0;
11069 if (ArrayEltSize == 1) {
11070 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011071 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011072 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011073 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011074 Scale = CI;
11075 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11076 if (Inst->getOpcode() == Instruction::Shl &&
11077 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011078 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11079 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011080 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011081 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011082 NewIdx = Inst->getOperand(0);
11083 } else if (Inst->getOpcode() == Instruction::Mul &&
11084 isa<ConstantInt>(Inst->getOperand(1))) {
11085 Scale = cast<ConstantInt>(Inst->getOperand(1));
11086 NewIdx = Inst->getOperand(0);
11087 }
11088 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011089
Chris Lattner7835cdd2005-09-13 18:36:04 +000011090 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011091 // out, perform the transformation. Note, we don't know whether Scale is
11092 // signed or not. We'll use unsigned version of division/modulo
11093 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011094 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011095 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011096 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011097 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011098 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011099 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11100 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011101 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011102 }
11103
11104 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011105 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011106 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011107 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011108 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11109 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11110 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011111 // The NewGEP must be pointer typed, so must the old one -> BitCast
11112 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011113 }
11114 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011115 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011116 }
Chris Lattner58407792009-01-09 04:53:57 +000011117
Chris Lattner46cd5a12009-01-09 05:44:56 +000011118 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011119 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011120 /// Y = gep X, <...constant indices...>
11121 /// into a gep of the original struct. This is important for SROA and alias
11122 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011123 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011124 if (TD &&
11125 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011126 // Determine how much the GEP moves the pointer. We are guaranteed to get
11127 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011128 ConstantInt *OffsetV =
11129 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011130 int64_t Offset = OffsetV->getSExtValue();
11131
11132 // If this GEP instruction doesn't move the pointer, just replace the GEP
11133 // with a bitcast of the real input to the dest type.
11134 if (Offset == 0) {
11135 // If the bitcast is of an allocation, and the allocation will be
11136 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011137 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11138 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011139 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11140 if (Instruction *I = visitBitCast(*BCI)) {
11141 if (I != BCI) {
11142 I->takeName(BCI);
11143 BCI->getParent()->getInstList().insert(BCI, I);
11144 ReplaceInstUsesWith(*BCI, I);
11145 }
11146 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011147 }
Chris Lattner58407792009-01-09 04:53:57 +000011148 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011149 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011150 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011151
11152 // Otherwise, if the offset is non-zero, we need to find out if there is a
11153 // field at Offset in 'A's type. If so, we can pull the cast through the
11154 // GEP.
11155 SmallVector<Value*, 8> NewIndices;
11156 const Type *InTy =
11157 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011158 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011159 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11160 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11161 NewIndices.end()) :
11162 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11163 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011164
11165 if (NGEP->getType() == GEP.getType())
11166 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011167 NGEP->takeName(&GEP);
11168 return new BitCastInst(NGEP, GEP.getType());
11169 }
Chris Lattner58407792009-01-09 04:53:57 +000011170 }
11171 }
11172
Chris Lattner8a2a3112001-12-14 16:52:21 +000011173 return 0;
11174}
11175
Chris Lattner0864acf2002-11-04 16:18:53 +000011176Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11177 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011178 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011179 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11180 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011181 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011182 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011183
11184 // Create and insert the replacement instruction...
11185 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011186 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011187 else {
11188 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011189 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011190 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011191 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011192
Chris Lattner0864acf2002-11-04 16:18:53 +000011193 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011194 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011195 //
11196 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011197 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011198
11199 // Now that I is pointing to the first non-allocation-inst in the block,
11200 // insert our getelementptr instruction...
11201 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011202 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011203 Value *Idx[2];
11204 Idx[0] = NullIdx;
11205 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011206 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11207 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011208
11209 // Now make everything use the getelementptr instead of the original
11210 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011211 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011212 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011213 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011214 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011215 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011216
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011217 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011218 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011219 // Note that we only do this for alloca's, because malloc should allocate
11220 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011221 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011222 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011223
11224 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11225 if (AI.getAlignment() == 0)
11226 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11227 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011228
Chris Lattner0864acf2002-11-04 16:18:53 +000011229 return 0;
11230}
11231
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011232Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11233 Value *Op = FI.getOperand(0);
11234
Chris Lattner17be6352004-10-18 02:59:09 +000011235 // free undef -> unreachable.
11236 if (isa<UndefValue>(Op)) {
11237 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011238 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011239 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011240 return EraseInstFromFunction(FI);
11241 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011242
Chris Lattner6160e852004-02-28 04:57:37 +000011243 // If we have 'free null' delete the instruction. This can happen in stl code
11244 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011245 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011246 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011247
11248 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11249 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11250 FI.setOperand(0, CI->getOperand(0));
11251 return &FI;
11252 }
11253
11254 // Change free (gep X, 0,0,0,0) into free(X)
11255 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11256 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011257 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011258 FI.setOperand(0, GEPI->getOperand(0));
11259 return &FI;
11260 }
11261 }
11262
11263 // Change free(malloc) into nothing, if the malloc has a single use.
11264 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11265 if (MI->hasOneUse()) {
11266 EraseInstFromFunction(FI);
11267 return EraseInstFromFunction(*MI);
11268 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011269 if (isMalloc(Op)) {
11270 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11271 if (Op->hasOneUse() && CI->hasOneUse()) {
11272 EraseInstFromFunction(FI);
11273 EraseInstFromFunction(*CI);
11274 return EraseInstFromFunction(*cast<Instruction>(Op));
11275 }
11276 } else {
11277 // Op is a call to malloc
11278 if (Op->hasOneUse()) {
11279 EraseInstFromFunction(FI);
11280 return EraseInstFromFunction(*cast<Instruction>(Op));
11281 }
11282 }
11283 }
Chris Lattner6160e852004-02-28 04:57:37 +000011284
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011285 return 0;
11286}
11287
11288
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011289/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011290static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011291 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011292 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011293 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011294 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011295
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011296 if (TD) {
11297 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11298 // Instead of loading constant c string, use corresponding integer value
11299 // directly if string length is small enough.
11300 std::string Str;
11301 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11302 unsigned len = Str.length();
11303 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11304 unsigned numBits = Ty->getPrimitiveSizeInBits();
11305 // Replace LI with immediate integer store.
11306 if ((numBits >> 3) == len + 1) {
11307 APInt StrVal(numBits, 0);
11308 APInt SingleChar(numBits, 0);
11309 if (TD->isLittleEndian()) {
11310 for (signed i = len-1; i >= 0; i--) {
11311 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11312 StrVal = (StrVal << 8) | SingleChar;
11313 }
11314 } else {
11315 for (unsigned i = 0; i < len; i++) {
11316 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11317 StrVal = (StrVal << 8) | SingleChar;
11318 }
11319 // Append NULL at the end.
11320 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011321 StrVal = (StrVal << 8) | SingleChar;
11322 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011323 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011324 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011325 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011326 }
11327 }
11328 }
11329
Mon P Wang6753f952009-02-07 22:19:29 +000011330 const PointerType *DestTy = cast<PointerType>(CI->getType());
11331 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011332 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011333
11334 // If the address spaces don't match, don't eliminate the cast.
11335 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11336 return 0;
11337
Chris Lattnerb89e0712004-07-13 01:49:43 +000011338 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011339
Reid Spencer42230162007-01-22 05:51:25 +000011340 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011341 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011342 // If the source is an array, the code below will not succeed. Check to
11343 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11344 // constants.
11345 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11346 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11347 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011348 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011349 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011350 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011351 SrcTy = cast<PointerType>(CastOp->getType());
11352 SrcPTy = SrcTy->getElementType();
11353 }
11354
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011355 if (IC.getTargetData() &&
11356 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011357 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011358 // Do not allow turning this into a load of an integer, which is then
11359 // casted to a pointer, this pessimizes pointer analysis a lot.
11360 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011361 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11362 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011363
Chris Lattnerf9527852005-01-31 04:50:46 +000011364 // Okay, we are casting from one integer or pointer type to another of
11365 // the same size. Instead of casting the pointer before the load, cast
11366 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011367 Value *NewLoad =
11368 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011369 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011370 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011371 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011372 }
11373 }
11374 return 0;
11375}
11376
Chris Lattner833b8a42003-06-26 05:06:25 +000011377Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11378 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011379
Dan Gohman9941f742007-07-20 16:34:21 +000011380 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011381 if (TD) {
11382 unsigned KnownAlign =
11383 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11384 if (KnownAlign >
11385 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11386 LI.getAlignment()))
11387 LI.setAlignment(KnownAlign);
11388 }
Dan Gohman9941f742007-07-20 16:34:21 +000011389
Chris Lattner963f4ba2009-08-30 20:36:46 +000011390 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011391 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011392 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011393 return Res;
11394
11395 // None of the following transforms are legal for volatile loads.
11396 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011397
Dan Gohman2276a7b2008-10-15 23:19:35 +000011398 // Do really simple store-to-load forwarding and load CSE, to catch cases
11399 // where there are several consequtive memory accesses to the same location,
11400 // separated by a few arithmetic operations.
11401 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011402 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11403 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011404
Christopher Lambb15147e2007-12-29 07:56:53 +000011405 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11406 const Value *GEPI0 = GEPI->getOperand(0);
11407 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011408 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011409 // Insert a new store to null instruction before the load to indicate
11410 // that this code is not reachable. We do this instead of inserting
11411 // an unreachable instruction directly because we cannot modify the
11412 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011413 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011414 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011415 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011416 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011417 }
Chris Lattner37366c12005-05-01 04:24:53 +000011418
Chris Lattnere87597f2004-10-16 18:11:37 +000011419 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011420 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011421 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011422 if (isa<UndefValue>(C) ||
11423 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011424 // Insert a new store to null instruction before the load to indicate that
11425 // this code is not reachable. We do this instead of inserting an
11426 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011427 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011428 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011429 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011430 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011431
Chris Lattnere87597f2004-10-16 18:11:37 +000011432 // Instcombine load (constant global) into the value loaded.
11433 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011434 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011435 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011436
Chris Lattnere87597f2004-10-16 18:11:37 +000011437 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011438 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011439 if (CE->getOpcode() == Instruction::GetElementPtr) {
11440 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011441 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011442 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011443 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011444 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011445 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011446 if (CE->getOperand(0)->isNullValue()) {
11447 // Insert a new store to null instruction before the load to indicate
11448 // that this code is not reachable. We do this instead of inserting
11449 // an unreachable instruction directly because we cannot modify the
11450 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011451 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011452 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011453 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011454 }
11455
Reid Spencer3da59db2006-11-27 01:05:10 +000011456 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011457 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011458 return Res;
11459 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011460 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011461 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011462
11463 // If this load comes from anywhere in a constant global, and if the global
11464 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011465 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011466 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011467 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011468 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011469 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011470 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011471 }
11472 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011473
Chris Lattner37366c12005-05-01 04:24:53 +000011474 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011475 // Change select and PHI nodes to select values instead of addresses: this
11476 // helps alias analysis out a lot, allows many others simplifications, and
11477 // exposes redundancy in the code.
11478 //
11479 // Note that we cannot do the transformation unless we know that the
11480 // introduced loads cannot trap! Something like this is valid as long as
11481 // the condition is always false: load (select bool %C, int* null, int* %G),
11482 // but it would not be valid if we transformed it to load from null
11483 // unconditionally.
11484 //
11485 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11486 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011487 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11488 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011489 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11490 SI->getOperand(1)->getName()+".val");
11491 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11492 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011493 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011494 }
11495
Chris Lattner684fe212004-09-23 15:46:00 +000011496 // load (select (cond, null, P)) -> load P
11497 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11498 if (C->isNullValue()) {
11499 LI.setOperand(0, SI->getOperand(2));
11500 return &LI;
11501 }
11502
11503 // load (select (cond, P, null)) -> load P
11504 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11505 if (C->isNullValue()) {
11506 LI.setOperand(0, SI->getOperand(1));
11507 return &LI;
11508 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011509 }
11510 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011511 return 0;
11512}
11513
Reid Spencer55af2b52007-01-19 21:20:31 +000011514/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011515/// when possible. This makes it generally easy to do alias analysis and/or
11516/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011517static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11518 User *CI = cast<User>(SI.getOperand(1));
11519 Value *CastOp = CI->getOperand(0);
11520
11521 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011522 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11523 if (SrcTy == 0) return 0;
11524
11525 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011526
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011527 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11528 return 0;
11529
Chris Lattner3914f722009-01-24 01:00:13 +000011530 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11531 /// to its first element. This allows us to handle things like:
11532 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11533 /// on 32-bit hosts.
11534 SmallVector<Value*, 4> NewGEPIndices;
11535
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011536 // If the source is an array, the code below will not succeed. Check to
11537 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11538 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011539 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11540 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011541 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011542 NewGEPIndices.push_back(Zero);
11543
11544 while (1) {
11545 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011546 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011547 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011548 NewGEPIndices.push_back(Zero);
11549 SrcPTy = STy->getElementType(0);
11550 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11551 NewGEPIndices.push_back(Zero);
11552 SrcPTy = ATy->getElementType();
11553 } else {
11554 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011555 }
Chris Lattner3914f722009-01-24 01:00:13 +000011556 }
11557
Owen Andersondebcb012009-07-29 22:17:13 +000011558 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011559 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011560
11561 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11562 return 0;
11563
Chris Lattner71759c42009-01-16 20:12:52 +000011564 // If the pointers point into different address spaces or if they point to
11565 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011566 if (!IC.getTargetData() ||
11567 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011568 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011569 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11570 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011571 return 0;
11572
11573 // Okay, we are casting from one integer or pointer type to another of
11574 // the same size. Instead of casting the pointer before
11575 // the store, cast the value to be stored.
11576 Value *NewCast;
11577 Value *SIOp0 = SI.getOperand(0);
11578 Instruction::CastOps opcode = Instruction::BitCast;
11579 const Type* CastSrcTy = SIOp0->getType();
11580 const Type* CastDstTy = SrcPTy;
11581 if (isa<PointerType>(CastDstTy)) {
11582 if (CastSrcTy->isInteger())
11583 opcode = Instruction::IntToPtr;
11584 } else if (isa<IntegerType>(CastDstTy)) {
11585 if (isa<PointerType>(SIOp0->getType()))
11586 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011587 }
Chris Lattner3914f722009-01-24 01:00:13 +000011588
11589 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11590 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011591 if (!NewGEPIndices.empty())
11592 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11593 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011594
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011595 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11596 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011597 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011598}
11599
Chris Lattner4aebaee2008-11-27 08:56:30 +000011600/// equivalentAddressValues - Test if A and B will obviously have the same
11601/// value. This includes recognizing that %t0 and %t1 will have the same
11602/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011603/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011604/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011605/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011606/// %t2 = load i32* %t1
11607///
11608static bool equivalentAddressValues(Value *A, Value *B) {
11609 // Test if the values are trivially equivalent.
11610 if (A == B) return true;
11611
11612 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011613 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11614 // its only used to compare two uses within the same basic block, which
11615 // means that they'll always either have the same value or one of them
11616 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011617 if (isa<BinaryOperator>(A) ||
11618 isa<CastInst>(A) ||
11619 isa<PHINode>(A) ||
11620 isa<GetElementPtrInst>(A))
11621 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011622 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011623 return true;
11624
11625 // Otherwise they may not be equivalent.
11626 return false;
11627}
11628
Dale Johannesen4945c652009-03-03 21:26:39 +000011629// If this instruction has two uses, one of which is a llvm.dbg.declare,
11630// return the llvm.dbg.declare.
11631DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11632 if (!V->hasNUses(2))
11633 return 0;
11634 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11635 UI != E; ++UI) {
11636 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11637 return DI;
11638 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11639 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11640 return DI;
11641 }
11642 }
11643 return 0;
11644}
11645
Chris Lattner2f503e62005-01-31 05:36:43 +000011646Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11647 Value *Val = SI.getOperand(0);
11648 Value *Ptr = SI.getOperand(1);
11649
11650 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011651 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011652 ++NumCombined;
11653 return 0;
11654 }
Chris Lattner836692d2007-01-15 06:51:56 +000011655
11656 // If the RHS is an alloca with a single use, zapify the store, making the
11657 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011658 // If the RHS is an alloca with a two uses, the other one being a
11659 // llvm.dbg.declare, zapify the store and the declare, making the
11660 // alloca dead. We must do this to prevent declare's from affecting
11661 // codegen.
11662 if (!SI.isVolatile()) {
11663 if (Ptr->hasOneUse()) {
11664 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011665 EraseInstFromFunction(SI);
11666 ++NumCombined;
11667 return 0;
11668 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011669 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11670 if (isa<AllocaInst>(GEP->getOperand(0))) {
11671 if (GEP->getOperand(0)->hasOneUse()) {
11672 EraseInstFromFunction(SI);
11673 ++NumCombined;
11674 return 0;
11675 }
11676 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11677 EraseInstFromFunction(*DI);
11678 EraseInstFromFunction(SI);
11679 ++NumCombined;
11680 return 0;
11681 }
11682 }
11683 }
11684 }
11685 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11686 EraseInstFromFunction(*DI);
11687 EraseInstFromFunction(SI);
11688 ++NumCombined;
11689 return 0;
11690 }
Chris Lattner836692d2007-01-15 06:51:56 +000011691 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011692
Dan Gohman9941f742007-07-20 16:34:21 +000011693 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011694 if (TD) {
11695 unsigned KnownAlign =
11696 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11697 if (KnownAlign >
11698 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11699 SI.getAlignment()))
11700 SI.setAlignment(KnownAlign);
11701 }
Dan Gohman9941f742007-07-20 16:34:21 +000011702
Dale Johannesenacb51a32009-03-03 01:43:03 +000011703 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011704 // stores to the same location, separated by a few arithmetic operations. This
11705 // situation often occurs with bitfield accesses.
11706 BasicBlock::iterator BBI = &SI;
11707 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11708 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011709 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011710 // Don't count debug info directives, lest they affect codegen,
11711 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11712 // It is necessary for correctness to skip those that feed into a
11713 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011714 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011715 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011716 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011717 continue;
11718 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011719
11720 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11721 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011722 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11723 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011724 ++NumDeadStore;
11725 ++BBI;
11726 EraseInstFromFunction(*PrevSI);
11727 continue;
11728 }
11729 break;
11730 }
11731
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011732 // If this is a load, we have to stop. However, if the loaded value is from
11733 // the pointer we're loading and is producing the pointer we're storing,
11734 // then *this* store is dead (X = load P; store X -> P).
11735 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011736 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11737 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011738 EraseInstFromFunction(SI);
11739 ++NumCombined;
11740 return 0;
11741 }
11742 // Otherwise, this is a load from some other location. Stores before it
11743 // may not be dead.
11744 break;
11745 }
11746
Chris Lattner9ca96412006-02-08 03:25:32 +000011747 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011748 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011749 break;
11750 }
11751
11752
11753 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011754
11755 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011756 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011757 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011758 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011759 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011760 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011761 ++NumCombined;
11762 }
11763 return 0; // Do not modify these!
11764 }
11765
11766 // store undef, Ptr -> noop
11767 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011768 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011769 ++NumCombined;
11770 return 0;
11771 }
11772
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011773 // If the pointer destination is a cast, see if we can fold the cast into the
11774 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011775 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011776 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11777 return Res;
11778 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011779 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011780 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11781 return Res;
11782
Chris Lattner408902b2005-09-12 23:23:25 +000011783
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011784 // If this store is the last instruction in the basic block (possibly
11785 // excepting debug info instructions and the pointer bitcasts that feed
11786 // into them), and if the block ends with an unconditional branch, try
11787 // to move it to the successor block.
11788 BBI = &SI;
11789 do {
11790 ++BBI;
11791 } while (isa<DbgInfoIntrinsic>(BBI) ||
11792 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011793 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011794 if (BI->isUnconditional())
11795 if (SimplifyStoreAtEndOfBlock(SI))
11796 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011797
Chris Lattner2f503e62005-01-31 05:36:43 +000011798 return 0;
11799}
11800
Chris Lattner3284d1f2007-04-15 00:07:55 +000011801/// SimplifyStoreAtEndOfBlock - Turn things like:
11802/// if () { *P = v1; } else { *P = v2 }
11803/// into a phi node with a store in the successor.
11804///
Chris Lattner31755a02007-04-15 01:02:18 +000011805/// Simplify things like:
11806/// *P = v1; if () { *P = v2; }
11807/// into a phi node with a store in the successor.
11808///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011809bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11810 BasicBlock *StoreBB = SI.getParent();
11811
11812 // Check to see if the successor block has exactly two incoming edges. If
11813 // so, see if the other predecessor contains a store to the same location.
11814 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011815 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011816
11817 // Determine whether Dest has exactly two predecessors and, if so, compute
11818 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011819 pred_iterator PI = pred_begin(DestBB);
11820 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011821 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011822 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011823 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011824 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011825 return false;
11826
11827 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011828 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011829 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011830 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011831 }
Chris Lattner31755a02007-04-15 01:02:18 +000011832 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011833 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011834
11835 // Bail out if all the relevant blocks aren't distinct (this can happen,
11836 // for example, if SI is in an infinite loop)
11837 if (StoreBB == DestBB || OtherBB == DestBB)
11838 return false;
11839
Chris Lattner31755a02007-04-15 01:02:18 +000011840 // Verify that the other block ends in a branch and is not otherwise empty.
11841 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011842 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011843 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011844 return false;
11845
Chris Lattner31755a02007-04-15 01:02:18 +000011846 // If the other block ends in an unconditional branch, check for the 'if then
11847 // else' case. there is an instruction before the branch.
11848 StoreInst *OtherStore = 0;
11849 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011850 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011851 // Skip over debugging info.
11852 while (isa<DbgInfoIntrinsic>(BBI) ||
11853 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11854 if (BBI==OtherBB->begin())
11855 return false;
11856 --BBI;
11857 }
11858 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011859 OtherStore = dyn_cast<StoreInst>(BBI);
11860 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11861 return false;
11862 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011863 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011864 // destinations is StoreBB, then we have the if/then case.
11865 if (OtherBr->getSuccessor(0) != StoreBB &&
11866 OtherBr->getSuccessor(1) != StoreBB)
11867 return false;
11868
11869 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011870 // if/then triangle. See if there is a store to the same ptr as SI that
11871 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011872 for (;; --BBI) {
11873 // Check to see if we find the matching store.
11874 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11875 if (OtherStore->getOperand(1) != SI.getOperand(1))
11876 return false;
11877 break;
11878 }
Eli Friedman6903a242008-06-13 22:02:12 +000011879 // If we find something that may be using or overwriting the stored
11880 // value, or if we run out of instructions, we can't do the xform.
11881 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011882 BBI == OtherBB->begin())
11883 return false;
11884 }
11885
11886 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011887 // make sure nothing reads or overwrites the stored value in
11888 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011889 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11890 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011891 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011892 return false;
11893 }
11894 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011895
Chris Lattner31755a02007-04-15 01:02:18 +000011896 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011897 Value *MergedVal = OtherStore->getOperand(0);
11898 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011899 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011900 PN->reserveOperandSpace(2);
11901 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011902 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11903 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011904 }
11905
11906 // Advance to a place where it is safe to insert the new store and
11907 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011908 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011909 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11910 OtherStore->isVolatile()), *BBI);
11911
11912 // Nuke the old stores.
11913 EraseInstFromFunction(SI);
11914 EraseInstFromFunction(*OtherStore);
11915 ++NumCombined;
11916 return true;
11917}
11918
Chris Lattner2f503e62005-01-31 05:36:43 +000011919
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011920Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11921 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011922 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011923 BasicBlock *TrueDest;
11924 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011925 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011926 !isa<Constant>(X)) {
11927 // Swap Destinations and condition...
11928 BI.setCondition(X);
11929 BI.setSuccessor(0, FalseDest);
11930 BI.setSuccessor(1, TrueDest);
11931 return &BI;
11932 }
11933
Reid Spencere4d87aa2006-12-23 06:05:41 +000011934 // Cannonicalize fcmp_one -> fcmp_oeq
11935 FCmpInst::Predicate FPred; Value *Y;
11936 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011937 TrueDest, FalseDest)) &&
11938 BI.getCondition()->hasOneUse())
11939 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11940 FPred == FCmpInst::FCMP_OGE) {
11941 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11942 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11943
11944 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011945 BI.setSuccessor(0, FalseDest);
11946 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011947 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011948 return &BI;
11949 }
11950
11951 // Cannonicalize icmp_ne -> icmp_eq
11952 ICmpInst::Predicate IPred;
11953 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011954 TrueDest, FalseDest)) &&
11955 BI.getCondition()->hasOneUse())
11956 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11957 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11958 IPred == ICmpInst::ICMP_SGE) {
11959 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11960 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11961 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011962 BI.setSuccessor(0, FalseDest);
11963 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011964 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011965 return &BI;
11966 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011967
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011968 return 0;
11969}
Chris Lattner0864acf2002-11-04 16:18:53 +000011970
Chris Lattner46238a62004-07-03 00:26:11 +000011971Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11972 Value *Cond = SI.getCondition();
11973 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11974 if (I->getOpcode() == Instruction::Add)
11975 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11976 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11977 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011978 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011979 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011980 AddRHS));
11981 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011982 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011983 return &SI;
11984 }
11985 }
11986 return 0;
11987}
11988
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011989Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011990 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011991
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011992 if (!EV.hasIndices())
11993 return ReplaceInstUsesWith(EV, Agg);
11994
11995 if (Constant *C = dyn_cast<Constant>(Agg)) {
11996 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011997 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011998
11999 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000012000 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012001
12002 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12003 // Extract the element indexed by the first index out of the constant
12004 Value *V = C->getOperand(*EV.idx_begin());
12005 if (EV.getNumIndices() > 1)
12006 // Extract the remaining indices out of the constant indexed by the
12007 // first index
12008 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12009 else
12010 return ReplaceInstUsesWith(EV, V);
12011 }
12012 return 0; // Can't handle other constants
12013 }
12014 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12015 // We're extracting from an insertvalue instruction, compare the indices
12016 const unsigned *exti, *exte, *insi, *inse;
12017 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12018 exte = EV.idx_end(), inse = IV->idx_end();
12019 exti != exte && insi != inse;
12020 ++exti, ++insi) {
12021 if (*insi != *exti)
12022 // The insert and extract both reference distinctly different elements.
12023 // This means the extract is not influenced by the insert, and we can
12024 // replace the aggregate operand of the extract with the aggregate
12025 // operand of the insert. i.e., replace
12026 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12027 // %E = extractvalue { i32, { i32 } } %I, 0
12028 // with
12029 // %E = extractvalue { i32, { i32 } } %A, 0
12030 return ExtractValueInst::Create(IV->getAggregateOperand(),
12031 EV.idx_begin(), EV.idx_end());
12032 }
12033 if (exti == exte && insi == inse)
12034 // Both iterators are at the end: Index lists are identical. Replace
12035 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12036 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12037 // with "i32 42"
12038 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12039 if (exti == exte) {
12040 // The extract list is a prefix of the insert list. i.e. replace
12041 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12042 // %E = extractvalue { i32, { i32 } } %I, 1
12043 // with
12044 // %X = extractvalue { i32, { i32 } } %A, 1
12045 // %E = insertvalue { i32 } %X, i32 42, 0
12046 // by switching the order of the insert and extract (though the
12047 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012048 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12049 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012050 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12051 insi, inse);
12052 }
12053 if (insi == inse)
12054 // The insert list is a prefix of the extract list
12055 // We can simply remove the common indices from the extract and make it
12056 // operate on the inserted value instead of the insertvalue result.
12057 // i.e., replace
12058 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12059 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12060 // with
12061 // %E extractvalue { i32 } { i32 42 }, 0
12062 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12063 exti, exte);
12064 }
12065 // Can't simplify extracts from other values. Note that nested extracts are
12066 // already simplified implicitely by the above (extract ( extract (insert) )
12067 // will be translated into extract ( insert ( extract ) ) first and then just
12068 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012069 return 0;
12070}
12071
Chris Lattner220b0cf2006-03-05 00:22:33 +000012072/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12073/// is to leave as a vector operation.
12074static bool CheapToScalarize(Value *V, bool isConstant) {
12075 if (isa<ConstantAggregateZero>(V))
12076 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012077 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012078 if (isConstant) return true;
12079 // If all elts are the same, we can extract.
12080 Constant *Op0 = C->getOperand(0);
12081 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12082 if (C->getOperand(i) != Op0)
12083 return false;
12084 return true;
12085 }
12086 Instruction *I = dyn_cast<Instruction>(V);
12087 if (!I) return false;
12088
12089 // Insert element gets simplified to the inserted element or is deleted if
12090 // this is constant idx extract element and its a constant idx insertelt.
12091 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12092 isa<ConstantInt>(I->getOperand(2)))
12093 return true;
12094 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12095 return true;
12096 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12097 if (BO->hasOneUse() &&
12098 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12099 CheapToScalarize(BO->getOperand(1), isConstant)))
12100 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012101 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12102 if (CI->hasOneUse() &&
12103 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12104 CheapToScalarize(CI->getOperand(1), isConstant)))
12105 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012106
12107 return false;
12108}
12109
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012110/// Read and decode a shufflevector mask.
12111///
12112/// It turns undef elements into values that are larger than the number of
12113/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012114static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12115 unsigned NElts = SVI->getType()->getNumElements();
12116 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12117 return std::vector<unsigned>(NElts, 0);
12118 if (isa<UndefValue>(SVI->getOperand(2)))
12119 return std::vector<unsigned>(NElts, 2*NElts);
12120
12121 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012122 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012123 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12124 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012125 Result.push_back(NElts*2); // undef -> 8
12126 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012127 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012128 return Result;
12129}
12130
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012131/// FindScalarElement - Given a vector and an element number, see if the scalar
12132/// value is already around as a register, for example if it were inserted then
12133/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012134static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012135 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012136 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12137 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012138 unsigned Width = PTy->getNumElements();
12139 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012140 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012141
12142 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012143 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012144 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012145 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012146 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012147 return CP->getOperand(EltNo);
12148 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12149 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012150 if (!isa<ConstantInt>(III->getOperand(2)))
12151 return 0;
12152 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012153
12154 // If this is an insert to the element we are looking for, return the
12155 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012156 if (EltNo == IIElt)
12157 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012158
12159 // Otherwise, the insertelement doesn't modify the value, recurse on its
12160 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012161 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012162 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012163 unsigned LHSWidth =
12164 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012165 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012166 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012167 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012168 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012169 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012170 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012171 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012172 }
12173
12174 // Otherwise, we don't know.
12175 return 0;
12176}
12177
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012178Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012179 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012180 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012181 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012182
Dan Gohman07a96762007-07-16 14:29:03 +000012183 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012184 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012185 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012186
Reid Spencer9d6565a2007-02-15 02:26:10 +000012187 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012188 // If vector val is constant with all elements the same, replace EI with
12189 // that element. When the elements are not identical, we cannot replace yet
12190 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012191 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012192 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012193 if (C->getOperand(i) != op0) {
12194 op0 = 0;
12195 break;
12196 }
12197 if (op0)
12198 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012199 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012200
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012201 // If extracting a specified index from the vector, see if we can recursively
12202 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012203 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012204 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012205 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012206
12207 // If this is extracting an invalid index, turn this into undef, to avoid
12208 // crashing the code below.
12209 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012210 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012211
Chris Lattner867b99f2006-10-05 06:55:50 +000012212 // This instruction only demands the single element from the input vector.
12213 // If the input vector has a single use, simplify it based on this use
12214 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012215 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012216 APInt UndefElts(VectorWidth, 0);
12217 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012218 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012219 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012220 EI.setOperand(0, V);
12221 return &EI;
12222 }
12223 }
12224
Owen Andersond672ecb2009-07-03 00:17:18 +000012225 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012226 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012227
12228 // If the this extractelement is directly using a bitcast from a vector of
12229 // the same number of elements, see if we can find the source element from
12230 // it. In this case, we will end up needing to bitcast the scalars.
12231 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12232 if (const VectorType *VT =
12233 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12234 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012235 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12236 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012237 return new BitCastInst(Elt, EI.getType());
12238 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012239 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012240
Chris Lattner73fa49d2006-05-25 22:53:38 +000012241 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012242 // Push extractelement into predecessor operation if legal and
12243 // profitable to do so
12244 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12245 if (I->hasOneUse() &&
12246 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12247 Value *newEI0 =
12248 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12249 EI.getName()+".lhs");
12250 Value *newEI1 =
12251 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12252 EI.getName()+".rhs");
12253 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012254 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012255 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012256 // Extracting the inserted element?
12257 if (IE->getOperand(2) == EI.getOperand(1))
12258 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12259 // If the inserted and extracted elements are constants, they must not
12260 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012261 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012262 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012263 EI.setOperand(0, IE->getOperand(0));
12264 return &EI;
12265 }
12266 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12267 // If this is extracting an element from a shufflevector, figure out where
12268 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012269 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12270 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012271 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012272 unsigned LHSWidth =
12273 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12274
12275 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012276 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012277 else if (SrcIdx < LHSWidth*2) {
12278 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012279 Src = SVI->getOperand(1);
12280 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012281 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012282 }
Eric Christophera3500da2009-07-25 02:28:41 +000012283 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012284 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12285 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012286 }
12287 }
Eli Friedman2451a642009-07-18 23:06:53 +000012288 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012289 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012290 return 0;
12291}
12292
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012293/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12294/// elements from either LHS or RHS, return the shuffle mask and true.
12295/// Otherwise, return false.
12296static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012297 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012298 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012299 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12300 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012301 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012302
12303 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012304 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012305 return true;
12306 } else if (V == LHS) {
12307 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012308 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012309 return true;
12310 } else if (V == RHS) {
12311 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012312 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012313 return true;
12314 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12315 // If this is an insert of an extract from some other vector, include it.
12316 Value *VecOp = IEI->getOperand(0);
12317 Value *ScalarOp = IEI->getOperand(1);
12318 Value *IdxOp = IEI->getOperand(2);
12319
Chris Lattnerd929f062006-04-27 21:14:21 +000012320 if (!isa<ConstantInt>(IdxOp))
12321 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012322 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012323
12324 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12325 // Okay, we can handle this if the vector we are insertinting into is
12326 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012327 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012328 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012329 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012330 return true;
12331 }
12332 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12333 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012334 EI->getOperand(0)->getType() == V->getType()) {
12335 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012336 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012337
12338 // This must be extracting from either LHS or RHS.
12339 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12340 // Okay, we can handle this if the vector we are insertinting into is
12341 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012342 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012343 // If so, update the mask to reflect the inserted value.
12344 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012345 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012346 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012347 } else {
12348 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012349 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012350 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012351
12352 }
12353 return true;
12354 }
12355 }
12356 }
12357 }
12358 }
12359 // TODO: Handle shufflevector here!
12360
12361 return false;
12362}
12363
12364/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12365/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12366/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012367static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012368 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012369 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012370 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012371 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012372 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012373
12374 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012375 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012376 return V;
12377 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012378 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012379 return V;
12380 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12381 // If this is an insert of an extract from some other vector, include it.
12382 Value *VecOp = IEI->getOperand(0);
12383 Value *ScalarOp = IEI->getOperand(1);
12384 Value *IdxOp = IEI->getOperand(2);
12385
12386 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12387 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12388 EI->getOperand(0)->getType() == V->getType()) {
12389 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012390 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12391 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012392
12393 // Either the extracted from or inserted into vector must be RHSVec,
12394 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012395 if (EI->getOperand(0) == RHS || RHS == 0) {
12396 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012397 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012398 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012399 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012400 return V;
12401 }
12402
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012403 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012404 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12405 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012406 // Everything but the extracted element is replaced with the RHS.
12407 for (unsigned i = 0; i != NumElts; ++i) {
12408 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012409 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012410 }
12411 return V;
12412 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012413
12414 // If this insertelement is a chain that comes from exactly these two
12415 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012416 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12417 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012418 return EI->getOperand(0);
12419
Chris Lattnerefb47352006-04-15 01:39:45 +000012420 }
12421 }
12422 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012423 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012424
12425 // Otherwise, can't do anything fancy. Return an identity vector.
12426 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012427 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012428 return V;
12429}
12430
12431Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12432 Value *VecOp = IE.getOperand(0);
12433 Value *ScalarOp = IE.getOperand(1);
12434 Value *IdxOp = IE.getOperand(2);
12435
Chris Lattner599ded12007-04-09 01:11:16 +000012436 // Inserting an undef or into an undefined place, remove this.
12437 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12438 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012439
Chris Lattnerefb47352006-04-15 01:39:45 +000012440 // If the inserted element was extracted from some other vector, and if the
12441 // indexes are constant, try to turn this into a shufflevector operation.
12442 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12443 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12444 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012445 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012446 unsigned ExtractedIdx =
12447 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012448 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012449
12450 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12451 return ReplaceInstUsesWith(IE, VecOp);
12452
12453 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012454 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012455
12456 // If we are extracting a value from a vector, then inserting it right
12457 // back into the same place, just use the input vector.
12458 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12459 return ReplaceInstUsesWith(IE, VecOp);
12460
12461 // We could theoretically do this for ANY input. However, doing so could
12462 // turn chains of insertelement instructions into a chain of shufflevector
12463 // instructions, and right now we do not merge shufflevectors. As such,
12464 // only do this in a situation where it is clear that there is benefit.
12465 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12466 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12467 // the values of VecOp, except then one read from EIOp0.
12468 // Build a new shuffle mask.
12469 std::vector<Constant*> Mask;
12470 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012471 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012472 else {
12473 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012474 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012475 NumVectorElts));
12476 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012477 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012478 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012479 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012480 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012481 }
12482
12483 // If this insertelement isn't used by some other insertelement, turn it
12484 // (and any insertelements it points to), into one big shuffle.
12485 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12486 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012487 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012488 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012489 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012490 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012491 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012492 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012493 }
12494 }
12495 }
12496
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012497 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12498 APInt UndefElts(VWidth, 0);
12499 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12500 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12501 return &IE;
12502
Chris Lattnerefb47352006-04-15 01:39:45 +000012503 return 0;
12504}
12505
12506
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012507Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12508 Value *LHS = SVI.getOperand(0);
12509 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012510 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012511
12512 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012513
Chris Lattner867b99f2006-10-05 06:55:50 +000012514 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012515 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012516 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012517
Dan Gohman488fbfc2008-09-09 18:11:14 +000012518 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012519
12520 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12521 return 0;
12522
Evan Cheng388df622009-02-03 10:05:09 +000012523 APInt UndefElts(VWidth, 0);
12524 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12525 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012526 LHS = SVI.getOperand(0);
12527 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012528 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012529 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012530
Chris Lattner863bcff2006-05-25 23:48:38 +000012531 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12532 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12533 if (LHS == RHS || isa<UndefValue>(LHS)) {
12534 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012535 // shuffle(undef,undef,mask) -> undef.
12536 return ReplaceInstUsesWith(SVI, LHS);
12537 }
12538
Chris Lattner863bcff2006-05-25 23:48:38 +000012539 // Remap any references to RHS to use LHS.
12540 std::vector<Constant*> Elts;
12541 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012542 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012543 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012544 else {
12545 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012546 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012547 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012548 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012549 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012550 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012551 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012552 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012553 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012554 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012555 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012556 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012557 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012558 LHS = SVI.getOperand(0);
12559 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012560 MadeChange = true;
12561 }
12562
Chris Lattner7b2e27922006-05-26 00:29:06 +000012563 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012564 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012565
Chris Lattner863bcff2006-05-25 23:48:38 +000012566 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12567 if (Mask[i] >= e*2) continue; // Ignore undef values.
12568 // Is this an identity shuffle of the LHS value?
12569 isLHSID &= (Mask[i] == i);
12570
12571 // Is this an identity shuffle of the RHS value?
12572 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012573 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012574
Chris Lattner863bcff2006-05-25 23:48:38 +000012575 // Eliminate identity shuffles.
12576 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12577 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012578
Chris Lattner7b2e27922006-05-26 00:29:06 +000012579 // If the LHS is a shufflevector itself, see if we can combine it with this
12580 // one without producing an unusual shuffle. Here we are really conservative:
12581 // we are absolutely afraid of producing a shuffle mask not in the input
12582 // program, because the code gen may not be smart enough to turn a merged
12583 // shuffle into two specific shuffles: it may produce worse code. As such,
12584 // we only merge two shuffles if the result is one of the two input shuffle
12585 // masks. In this case, merging the shuffles just removes one instruction,
12586 // which we know is safe. This is good for things like turning:
12587 // (splat(splat)) -> splat.
12588 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12589 if (isa<UndefValue>(RHS)) {
12590 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12591
12592 std::vector<unsigned> NewMask;
12593 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12594 if (Mask[i] >= 2*e)
12595 NewMask.push_back(2*e);
12596 else
12597 NewMask.push_back(LHSMask[Mask[i]]);
12598
12599 // If the result mask is equal to the src shuffle or this shuffle mask, do
12600 // the replacement.
12601 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012602 unsigned LHSInNElts =
12603 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012604 std::vector<Constant*> Elts;
12605 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012606 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012607 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012608 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012609 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012610 }
12611 }
12612 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12613 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012614 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012615 }
12616 }
12617 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012618
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012619 return MadeChange ? &SVI : 0;
12620}
12621
12622
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012623
Chris Lattnerea1c4542004-12-08 23:43:58 +000012624
12625/// TryToSinkInstruction - Try to move the specified instruction from its
12626/// current block into the beginning of DestBlock, which can only happen if it's
12627/// safe to move the instruction past all of the instructions between it and the
12628/// end of its block.
12629static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12630 assert(I->hasOneUse() && "Invariants didn't hold!");
12631
Chris Lattner108e9022005-10-27 17:13:11 +000012632 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012633 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012634 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012635
Chris Lattnerea1c4542004-12-08 23:43:58 +000012636 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012637 if (isa<AllocaInst>(I) && I->getParent() ==
12638 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012639 return false;
12640
Chris Lattner96a52a62004-12-09 07:14:34 +000012641 // We can only sink load instructions if there is nothing between the load and
12642 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012643 if (I->mayReadFromMemory()) {
12644 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012645 Scan != E; ++Scan)
12646 if (Scan->mayWriteToMemory())
12647 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012648 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012649
Dan Gohman02dea8b2008-05-23 21:05:58 +000012650 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012651
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012652 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012653 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012654 ++NumSunkInst;
12655 return true;
12656}
12657
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012658
12659/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12660/// all reachable code to the worklist.
12661///
12662/// This has a couple of tricks to make the code faster and more powerful. In
12663/// particular, we constant fold and DCE instructions as we go, to avoid adding
12664/// them to the worklist (this significantly speeds up instcombine on code where
12665/// many instructions are dead or constant). Additionally, if we find a branch
12666/// whose condition is a known constant, we only visit the reachable successors.
12667///
12668static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012669 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012670 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012671 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012672 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012673 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012674
Chris Lattner2c7718a2007-03-23 19:17:18 +000012675 while (!Worklist.empty()) {
12676 BB = Worklist.back();
12677 Worklist.pop_back();
12678
12679 // We have now visited this block! If we've already been here, ignore it.
12680 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012681
12682 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012683 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12684 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012685
Chris Lattner2c7718a2007-03-23 19:17:18 +000012686 // DCE instruction if trivially dead.
12687 if (isInstructionTriviallyDead(Inst)) {
12688 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012689 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012690 Inst->eraseFromParent();
12691 continue;
12692 }
12693
12694 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012695 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012696 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12697 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012698 Inst->replaceAllUsesWith(C);
12699 ++NumConstProp;
12700 Inst->eraseFromParent();
12701 continue;
12702 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012703
Devang Patel7fe1dec2008-11-19 18:56:50 +000012704 // If there are two consecutive llvm.dbg.stoppoint calls then
12705 // it is likely that the optimizer deleted code in between these
12706 // two intrinsics.
12707 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12708 if (DBI_Next) {
12709 if (DBI_Prev
12710 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12711 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012712 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012713 DBI_Prev->eraseFromParent();
12714 }
12715 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012716 } else {
12717 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012718 }
12719
Chris Lattner7a1e9242009-08-30 06:13:40 +000012720 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012721 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012722
12723 // Recursively visit successors. If this is a branch or switch on a
12724 // constant, only visit the reachable successor.
12725 TerminatorInst *TI = BB->getTerminator();
12726 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12727 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12728 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012729 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012730 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012731 continue;
12732 }
12733 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12734 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12735 // See if this is an explicit destination.
12736 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12737 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012738 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012739 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012740 continue;
12741 }
12742
12743 // Otherwise it is the default destination.
12744 Worklist.push_back(SI->getSuccessor(0));
12745 continue;
12746 }
12747 }
12748
12749 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12750 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012751 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012752}
12753
Chris Lattnerec9c3582007-03-03 02:04:50 +000012754bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012755 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012756 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012757
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012758 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12759 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012760
Chris Lattnerb3d59702005-07-07 20:40:38 +000012761 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012762 // Do a depth-first traversal of the function, populate the worklist with
12763 // the reachable instructions. Ignore blocks that are not reachable. Keep
12764 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012765 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012766 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012767
Chris Lattnerb3d59702005-07-07 20:40:38 +000012768 // Do a quick scan over the function. If we find any blocks that are
12769 // unreachable, remove any instructions inside of them. This prevents
12770 // the instcombine code from having to deal with some bad special cases.
12771 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12772 if (!Visited.count(BB)) {
12773 Instruction *Term = BB->getTerminator();
12774 while (Term != BB->begin()) { // Remove instrs bottom-up
12775 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012776
Chris Lattnerbdff5482009-08-23 04:37:46 +000012777 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012778 // A debug intrinsic shouldn't force another iteration if we weren't
12779 // going to do one without it.
12780 if (!isa<DbgInfoIntrinsic>(I)) {
12781 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012782 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012783 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012784 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012785 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012786 I->eraseFromParent();
12787 }
12788 }
12789 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012790
Chris Lattner873ff012009-08-30 05:55:36 +000012791 while (!Worklist.isEmpty()) {
12792 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012793 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012794
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012795 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012796 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012797 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012798 EraseInstFromFunction(*I);
12799 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012800 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012801 continue;
12802 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012803
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012804 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012805 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012806 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012807
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012808 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012809 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012810 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012811 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012812 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012813 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012814 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012815
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012816 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012817 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012818 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12819 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012820 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12821 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012822 if (NewC != CE) {
12823 i->set(NewC);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012824 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012825 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012826 }
12827
Chris Lattnerea1c4542004-12-08 23:43:58 +000012828 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012829 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012830 BasicBlock *BB = I->getParent();
12831 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12832 if (UserParent != BB) {
12833 bool UserIsSuccessor = false;
12834 // See if the user is one of our successors.
12835 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12836 if (*SI == UserParent) {
12837 UserIsSuccessor = true;
12838 break;
12839 }
12840
12841 // If the user is one of our immediate successors, and if that successor
12842 // only has us as a predecessors (we'd have to split the critical edge
12843 // otherwise), we can keep going.
12844 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12845 next(pred_begin(UserParent)) == pred_end(UserParent))
12846 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012847 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012848 }
12849 }
12850
Chris Lattner74381062009-08-30 07:44:24 +000012851 // Now that we have an instruction, try combining it to simplify it.
12852 Builder->SetInsertPoint(I->getParent(), I);
12853
Reid Spencera9b81012007-03-26 17:44:01 +000012854#ifndef NDEBUG
12855 std::string OrigI;
12856#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012857 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012858
Chris Lattner90ac28c2002-08-02 19:29:35 +000012859 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012860 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012861 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012862 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012863 DEBUG(errs() << "IC: Old = " << *I << '\n'
12864 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012865
Chris Lattnerf523d062004-06-09 05:08:07 +000012866 // Everything uses the new instruction now.
12867 I->replaceAllUsesWith(Result);
12868
12869 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012870 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012871 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012872
Chris Lattner6934a042007-02-11 01:23:03 +000012873 // Move the name to the new instruction first.
12874 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012875
12876 // Insert the new instruction into the basic block...
12877 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012878 BasicBlock::iterator InsertPos = I;
12879
12880 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12881 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12882 ++InsertPos;
12883
12884 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012885
Chris Lattner7a1e9242009-08-30 06:13:40 +000012886 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012887 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012888#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012889 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12890 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012891#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012892
Chris Lattner90ac28c2002-08-02 19:29:35 +000012893 // If the instruction was modified, it's possible that it is now dead.
12894 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012895 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012896 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012897 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012898 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012899 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012900 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012901 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012902 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012903 }
12904 }
12905
Chris Lattner873ff012009-08-30 05:55:36 +000012906 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012907 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012908}
12909
Chris Lattnerec9c3582007-03-03 02:04:50 +000012910
12911bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012912 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012913 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012914
Chris Lattner74381062009-08-30 07:44:24 +000012915
12916 /// Builder - This is an IRBuilder that automatically inserts new
12917 /// instructions into the worklist when they are created.
12918 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12919 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12920 InstCombineIRInserter(Worklist));
12921 Builder = &TheBuilder;
12922
Chris Lattnerec9c3582007-03-03 02:04:50 +000012923 bool EverMadeChange = false;
12924
12925 // Iterate while there is work to do.
12926 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012927 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012928 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012929
12930 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012931 return EverMadeChange;
12932}
12933
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012934FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012935 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012936}