blob: 561527cbb461d78360e6fe9267798429ee1a899c [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 Lattner213cd612009-09-27 20:46:36 +0000391 //
392 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
393 // that would normally be unprofitable because they strongly encourage jump
394 // threading.
395 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000396
Chris Lattnerbac32862004-11-14 19:13:23 +0000397 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
398 // operator and they all are only used by the PHI, PHI together their
399 // inputs, and do the operation once, to the result of the PHI.
400 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000401 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000402 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
403
Chris Lattner7da52b22006-11-01 04:51:18 +0000404
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000405 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
406 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000407
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000408 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000409 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000410 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000411 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000412 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000413 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000414 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000415 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000416 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000417
Chris Lattnerafe91a52006-06-15 19:07:26 +0000418
Reid Spencerc55b2432006-12-13 18:21:21 +0000419 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000420
Dan Gohman6de29f82009-06-15 22:12:54 +0000421 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000422 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000423 unsigned GetOrEnforceKnownAlignment(Value *V,
424 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000425
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000426 };
Chris Lattner873ff012009-08-30 05:55:36 +0000427} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000428
Dan Gohman844731a2008-05-13 00:00:25 +0000429char InstCombiner::ID = 0;
430static RegisterPass<InstCombiner>
431X("instcombine", "Combine redundant instructions");
432
Chris Lattner4f98c562003-03-10 21:43:22 +0000433// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000434// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000435static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000436 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000437 if (BinaryOperator::isNeg(V) ||
438 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000439 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000440 return 3;
441 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000442 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000443 if (isa<Argument>(V)) return 3;
444 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000445}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000446
Chris Lattnerc8802d22003-03-11 00:12:48 +0000447// isOnlyUse - Return true if this instruction will be deleted if we stop using
448// it.
449static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000450 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000451}
452
Chris Lattner4cb170c2004-02-23 06:38:22 +0000453// getPromotedType - Return the specified type promoted as it would be to pass
454// though a va_arg area...
455static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000456 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
457 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000458 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000459 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000460 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000461}
462
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000463/// getBitCastOperand - If the specified operand is a CastInst, a constant
464/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
465/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000466static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000467 if (Operator *O = dyn_cast<Operator>(V)) {
468 if (O->getOpcode() == Instruction::BitCast)
469 return O->getOperand(0);
470 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
471 if (GEP->hasAllZeroIndices())
472 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000473 }
Chris Lattnereed48272005-09-13 00:40:14 +0000474 return 0;
475}
476
Reid Spencer3da59db2006-11-27 01:05:10 +0000477/// This function is a wrapper around CastInst::isEliminableCastPair. It
478/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000479static Instruction::CastOps
480isEliminableCastPair(
481 const CastInst *CI, ///< The first cast instruction
482 unsigned opcode, ///< The opcode of the second cast instruction
483 const Type *DstTy, ///< The target type for the second cast instruction
484 TargetData *TD ///< The target data for pointer size
485) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000486
Reid Spencer3da59db2006-11-27 01:05:10 +0000487 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
488 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000489
Reid Spencer3da59db2006-11-27 01:05:10 +0000490 // Get the opcodes of the two Cast instructions
491 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
492 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000493
Chris Lattnera0e69692009-03-24 18:35:40 +0000494 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000495 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000496 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000497
498 // We don't want to form an inttoptr or ptrtoint that converts to an integer
499 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000500 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000501 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000502 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000503 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000504 Res = 0;
505
506 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000507}
508
509/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
510/// in any code being generated. It does not require codegen if V is simple
511/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000512static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
513 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000514 if (V->getType() == Ty || isa<Constant>(V)) return false;
515
Chris Lattner01575b72006-05-25 23:24:33 +0000516 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000517 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000518 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000519 return false;
520 return true;
521}
522
Chris Lattner4f98c562003-03-10 21:43:22 +0000523// SimplifyCommutative - This performs a few simplifications for commutative
524// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000525//
Chris Lattner4f98c562003-03-10 21:43:22 +0000526// 1. Order operands such that they are listed from right (least complex) to
527// left (most complex). This puts constants before unary operators before
528// binary operators.
529//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000530// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
531// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000532//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000533bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000534 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000535 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000536 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000537
Chris Lattner4f98c562003-03-10 21:43:22 +0000538 if (!I.isAssociative()) return Changed;
539 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000540 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
541 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
542 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000543 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000544 cast<Constant>(I.getOperand(1)),
545 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000546 I.setOperand(0, Op->getOperand(0));
547 I.setOperand(1, Folded);
548 return true;
549 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
550 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
551 isOnlyUse(Op) && isOnlyUse(Op1)) {
552 Constant *C1 = cast<Constant>(Op->getOperand(1));
553 Constant *C2 = cast<Constant>(Op1->getOperand(1));
554
555 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000556 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000557 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000558 Op1->getOperand(0),
559 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000560 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000561 I.setOperand(0, New);
562 I.setOperand(1, Folded);
563 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000564 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000565 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000566 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000567}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000568
Reid Spencere4d87aa2006-12-23 06:05:41 +0000569/// SimplifyCompare - For a CmpInst this function just orders the operands
570/// so that theyare listed from right (least complex) to left (most complex).
571/// This puts constants before unary operators before binary operators.
572bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000573 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000574 return false;
575 I.swapOperands();
576 // Compare instructions are not associative so there's nothing else we can do.
577 return true;
578}
579
Chris Lattner8d969642003-03-10 23:06:50 +0000580// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
581// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000582//
Dan Gohman186a6362009-08-12 16:04:34 +0000583static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000584 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000585 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000586
Chris Lattner0ce85802004-12-14 20:08:06 +0000587 // Constants can be considered to be negated values if they can be folded.
588 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000589 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000590
591 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
592 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000593 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000594
Chris Lattner8d969642003-03-10 23:06:50 +0000595 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000596}
597
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000598// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
599// instruction if the LHS is a constant negative zero (which is the 'negate'
600// form).
601//
Dan Gohman186a6362009-08-12 16:04:34 +0000602static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000603 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000604 return BinaryOperator::getFNegArgument(V);
605
606 // Constants can be considered to be negated values if they can be folded.
607 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000608 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000609
610 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
611 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000612 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000613
614 return 0;
615}
616
Dan Gohman186a6362009-08-12 16:04:34 +0000617static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000618 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000619 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000620
621 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000623 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000624 return 0;
625}
626
Chris Lattnerc8802d22003-03-11 00:12:48 +0000627// dyn_castFoldableMul - If this value is a multiply that can be folded into
628// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000629// non-constant operand of the multiply, and set CST to point to the multiplier.
630// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000631//
Dan Gohman186a6362009-08-12 16:04:34 +0000632static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000633 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000634 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000635 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000636 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000637 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000638 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000639 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000640 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000641 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000642 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000643 CST = ConstantInt::get(V->getType()->getContext(),
644 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000645 return I->getOperand(0);
646 }
647 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000648 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000649}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000650
Reid Spencer7177c3a2007-03-25 05:33:51 +0000651/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000652static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000653 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000654 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000655}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000656/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000657static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000658 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000659 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000660}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000661/// MultiplyOverflows - True if the multiply can not be expressed in an int
662/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000663static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000664 uint32_t W = C1->getBitWidth();
665 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
666 if (sign) {
667 LHSExt.sext(W * 2);
668 RHSExt.sext(W * 2);
669 } else {
670 LHSExt.zext(W * 2);
671 RHSExt.zext(W * 2);
672 }
673
674 APInt MulExt = LHSExt * RHSExt;
675
676 if (sign) {
677 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
678 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
679 return MulExt.slt(Min) || MulExt.sgt(Max);
680 } else
681 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
682}
Chris Lattner955f3312004-09-28 21:48:02 +0000683
Reid Spencere7816b52007-03-08 01:52:58 +0000684
Chris Lattner255d8912006-02-11 09:31:47 +0000685/// ShrinkDemandedConstant - Check to see if the specified operand of the
686/// specified instruction is a constant integer. If so, check to see if there
687/// are any bits set in the constant that are not demanded. If so, shrink the
688/// constant and return true.
689static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000690 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000691 assert(I && "No instruction?");
692 assert(OpNo < I->getNumOperands() && "Operand index too large");
693
694 // If the operand is not a constant integer, nothing to do.
695 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
696 if (!OpC) return false;
697
698 // If there are no bits set that aren't demanded, nothing to do.
699 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
700 if ((~Demanded & OpC->getValue()) == 0)
701 return false;
702
703 // This instruction is producing bits that are not demanded. Shrink the RHS.
704 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000705 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000706 return true;
707}
708
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000709// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
710// set of known zero and one bits, compute the maximum and minimum values that
711// could have the specified known zero and known one bits, returning them in
712// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000713static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000714 const APInt& KnownOne,
715 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000716 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
717 KnownZero.getBitWidth() == Min.getBitWidth() &&
718 KnownZero.getBitWidth() == Max.getBitWidth() &&
719 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000720 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723 // bit if it is unknown.
724 Min = KnownOne;
725 Max = KnownOne|UnknownBits;
726
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727 if (UnknownBits.isNegative()) { // Sign bit is unknown
728 Min.set(Min.getBitWidth()-1);
729 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000730 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000731}
732
733// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734// a set of known zero and one bits, compute the maximum and minimum values that
735// could have the specified known zero and known one bits, returning them in
736// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000737static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000740 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
741 KnownZero.getBitWidth() == Min.getBitWidth() &&
742 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000743 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000744 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000745
746 // The minimum value is when the unknown bits are all zeros.
747 Min = KnownOne;
748 // The maximum value is when the unknown bits are all ones.
749 Max = KnownOne|UnknownBits;
750}
Chris Lattner255d8912006-02-11 09:31:47 +0000751
Chris Lattner886ab6c2009-01-31 08:15:18 +0000752/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
753/// SimplifyDemandedBits knows about. See if the instruction has any
754/// properties that allow us to simplify its operands.
755bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000756 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000757 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
758 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
759
760 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
761 KnownZero, KnownOne, 0);
762 if (V == 0) return false;
763 if (V == &Inst) return true;
764 ReplaceInstUsesWith(Inst, V);
765 return true;
766}
767
768/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
769/// specified instruction operand if possible, updating it in place. It returns
770/// true if it made any change and false otherwise.
771bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
772 APInt &KnownZero, APInt &KnownOne,
773 unsigned Depth) {
774 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
775 KnownZero, KnownOne, Depth);
776 if (NewVal == 0) return false;
777 U.set(NewVal);
778 return true;
779}
780
781
782/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
783/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000784/// that only the bits set in DemandedMask of the result of V are ever used
785/// downstream. Consequently, depending on the mask and V, it may be possible
786/// to replace V with a constant or one of its operands. In such cases, this
787/// function does the replacement and returns true. In all other cases, it
788/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000789/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000790/// to be zero in the expression. These are provided to potentially allow the
791/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
792/// the expression. KnownOne and KnownZero always follow the invariant that
793/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
794/// the bits in KnownOne and KnownZero may only be accurate for those bits set
795/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
796/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000797///
798/// This returns null if it did not change anything and it permits no
799/// simplification. This returns V itself if it did some simplification of V's
800/// operands based on the information about what bits are demanded. This returns
801/// some other non-null value if it found out that V is equal to another value
802/// in the context where the specified bits are demanded, but not for all users.
803Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
804 APInt &KnownZero, APInt &KnownOne,
805 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000806 assert(V != 0 && "Null pointer of Value???");
807 assert(Depth <= 6 && "Limit Search Depth");
808 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000809 const Type *VTy = V->getType();
810 assert((TD || !isa<PointerType>(VTy)) &&
811 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000812 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
813 (!VTy->isIntOrIntVector() ||
814 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000815 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000816 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000817 "Value *V, DemandedMask, KnownZero and KnownOne "
818 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000819 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
820 // We know all of the bits for a constant!
821 KnownOne = CI->getValue() & DemandedMask;
822 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000823 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000824 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000825 if (isa<ConstantPointerNull>(V)) {
826 // We know all of the bits for a constant!
827 KnownOne.clear();
828 KnownZero = DemandedMask;
829 return 0;
830 }
831
Chris Lattner08d2cc72009-01-31 07:26:06 +0000832 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000833 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000834 if (DemandedMask == 0) { // Not demanding any bits from V.
835 if (isa<UndefValue>(V))
836 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000837 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000838 }
839
Chris Lattner4598c942009-01-31 08:24:16 +0000840 if (Depth == 6) // Limit search depth.
841 return 0;
842
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000843 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
844 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
845
Dan Gohman1c8491e2009-04-25 17:12:48 +0000846 Instruction *I = dyn_cast<Instruction>(V);
847 if (!I) {
848 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
849 return 0; // Only analyze instructions.
850 }
851
Chris Lattner4598c942009-01-31 08:24:16 +0000852 // If there are multiple uses of this value and we aren't at the root, then
853 // we can't do any simplifications of the operands, because DemandedMask
854 // only reflects the bits demanded by *one* of the users.
855 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000856 // Despite the fact that we can't simplify this instruction in all User's
857 // context, we can at least compute the knownzero/knownone bits, and we can
858 // do simplifications that apply to *just* the one user if we know that
859 // this instruction has a simpler value in that context.
860 if (I->getOpcode() == Instruction::And) {
861 // If either the LHS or the RHS are Zero, the result is zero.
862 ComputeMaskedBits(I->getOperand(1), DemandedMask,
863 RHSKnownZero, RHSKnownOne, Depth+1);
864 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
865 LHSKnownZero, LHSKnownOne, Depth+1);
866
867 // If all of the demanded bits are known 1 on one side, return the other.
868 // These bits cannot contribute to the result of the 'and' in this
869 // context.
870 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
871 (DemandedMask & ~LHSKnownZero))
872 return I->getOperand(0);
873 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
874 (DemandedMask & ~RHSKnownZero))
875 return I->getOperand(1);
876
877 // If all of the demanded bits in the inputs are known zeros, return zero.
878 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000879 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000880
881 } else if (I->getOpcode() == Instruction::Or) {
882 // We can simplify (X|Y) -> X or Y in the user's context if we know that
883 // only bits from X or Y are demanded.
884
885 // If either the LHS or the RHS are One, the result is One.
886 ComputeMaskedBits(I->getOperand(1), DemandedMask,
887 RHSKnownZero, RHSKnownOne, Depth+1);
888 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
889 LHSKnownZero, LHSKnownOne, Depth+1);
890
891 // If all of the demanded bits are known zero on one side, return the
892 // other. These bits cannot contribute to the result of the 'or' in this
893 // context.
894 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
895 (DemandedMask & ~LHSKnownOne))
896 return I->getOperand(0);
897 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
898 (DemandedMask & ~RHSKnownOne))
899 return I->getOperand(1);
900
901 // If all of the potentially set bits on one side are known to be set on
902 // the other side, just use the 'other' side.
903 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
904 (DemandedMask & (~RHSKnownZero)))
905 return I->getOperand(0);
906 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
907 (DemandedMask & (~LHSKnownZero)))
908 return I->getOperand(1);
909 }
910
Chris Lattner4598c942009-01-31 08:24:16 +0000911 // Compute the KnownZero/KnownOne bits to simplify things downstream.
912 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
913 return 0;
914 }
915
916 // If this is the root being simplified, allow it to have multiple uses,
917 // just set the DemandedMask to all bits so that we can try to simplify the
918 // operands. This allows visitTruncInst (for example) to simplify the
919 // operand of a trunc without duplicating all the logic below.
920 if (Depth == 0 && !V->hasOneUse())
921 DemandedMask = APInt::getAllOnesValue(BitWidth);
922
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000924 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000925 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000926 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000927 case Instruction::And:
928 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000929 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
930 RHSKnownZero, RHSKnownOne, Depth+1) ||
931 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000932 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000933 return I;
934 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
935 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If all of the demanded bits are known 1 on one side, return the other.
938 // These bits cannot contribute to the result of the 'and'.
939 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
940 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000941 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
943 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000945
946 // If all of the demanded bits in the inputs are known zeros, return zero.
947 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000948 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000949
950 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000951 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000953
954 // Output known-1 bits are only known if set in both the LHS & RHS.
955 RHSKnownOne &= LHSKnownOne;
956 // Output known-0 are known to be clear if zero in either the LHS | RHS.
957 RHSKnownZero |= LHSKnownZero;
958 break;
959 case Instruction::Or:
960 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000961 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
962 RHSKnownZero, RHSKnownOne, Depth+1) ||
963 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000964 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000965 return I;
966 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
967 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000968
969 // If all of the demanded bits are known zero on one side, return the other.
970 // These bits cannot contribute to the result of the 'or'.
971 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
972 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
975 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // If all of the potentially set bits on one side are known to be set on
979 // the other side, just use the 'other' side.
980 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
981 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000982 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000983 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
984 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000985 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000986
987 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // Output known-0 bits are only known if clear in both the LHS & RHS.
992 RHSKnownZero &= LHSKnownZero;
993 // Output known-1 are known to be set if set in either the LHS | RHS.
994 RHSKnownOne |= LHSKnownOne;
995 break;
996 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
998 RHSKnownZero, RHSKnownOne, Depth+1) ||
999 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001000 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 return I;
1002 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1003 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001004
1005 // If all of the demanded bits are known zero on one side, return the other.
1006 // These bits cannot contribute to the result of the 'xor'.
1007 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001008 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001009 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001010 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001011
1012 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1013 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1014 (RHSKnownOne & LHSKnownOne);
1015 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1016 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1017 (RHSKnownOne & LHSKnownZero);
1018
1019 // If all of the demanded bits are known to be zero on one side or the
1020 // other, turn this into an *inclusive* or.
1021 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001022 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1023 Instruction *Or =
1024 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1025 I->getName());
1026 return InsertNewInstBefore(Or, *I);
1027 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001028
1029 // If all of the demanded bits on one side are known, and all of the set
1030 // bits on that side are also known to be set on the other side, turn this
1031 // into an AND, as we know the bits will be cleared.
1032 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1033 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1034 // all known
1035 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001036 Constant *AndC = Constant::getIntegerValue(VTy,
1037 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001038 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001039 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001040 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001041 }
1042 }
1043
1044 // If the RHS is a constant, see if we can simplify it.
1045 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001046 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001047 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001048
1049 RHSKnownZero = KnownZeroOut;
1050 RHSKnownOne = KnownOneOut;
1051 break;
1052 }
1053 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1055 RHSKnownZero, RHSKnownOne, Depth+1) ||
1056 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001057 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001058 return I;
1059 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1060 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001061
1062 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001063 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1064 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001066
1067 // Only known if known in both the LHS and RHS.
1068 RHSKnownOne &= LHSKnownOne;
1069 RHSKnownZero &= LHSKnownZero;
1070 break;
1071 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001072 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001073 DemandedMask.zext(truncBf);
1074 RHSKnownZero.zext(truncBf);
1075 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001076 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001077 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001078 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001079 DemandedMask.trunc(BitWidth);
1080 RHSKnownZero.trunc(BitWidth);
1081 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 break;
1084 }
1085 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001086 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001087 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001088
1089 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1090 if (const VectorType *SrcVTy =
1091 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1092 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1093 // Don't touch a bitcast between vectors of different element counts.
1094 return false;
1095 } else
1096 // Don't touch a scalar-to-vector bitcast.
1097 return false;
1098 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1099 // Don't touch a vector-to-scalar bitcast.
1100 return false;
1101
Chris Lattner886ab6c2009-01-31 08:15:18 +00001102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001103 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001104 return I;
1105 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001106 break;
1107 case Instruction::ZExt: {
1108 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001109 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001110
Zhou Shengd48653a2007-03-29 04:45:55 +00001111 DemandedMask.trunc(SrcBitWidth);
1112 RHSKnownZero.trunc(SrcBitWidth);
1113 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001114 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001115 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001116 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001117 DemandedMask.zext(BitWidth);
1118 RHSKnownZero.zext(BitWidth);
1119 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 break;
1124 }
1125 case Instruction::SExt: {
1126 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001127 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001128
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001130 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001131
Zhou Sheng01542f32007-03-29 02:26:30 +00001132 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001133 // If any of the sign extended bits are demanded, we know that the sign
1134 // bit is demanded.
1135 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001136 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
Zhou Shengd48653a2007-03-29 04:45:55 +00001138 InputDemandedBits.trunc(SrcBitWidth);
1139 RHSKnownZero.trunc(SrcBitWidth);
1140 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001141 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001142 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001144 InputDemandedBits.zext(BitWidth);
1145 RHSKnownZero.zext(BitWidth);
1146 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001148
1149 // If the sign bit of the input is known set or clear, then we know the
1150 // top bits of the result.
1151
1152 // If the input sign bit is known zero, or if the NewBits are not demanded
1153 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001156 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1157 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001158 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001159 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001160 }
1161 break;
1162 }
1163 case Instruction::Add: {
1164 // Figure out what the input bits are. If the top bits of the and result
1165 // are not demanded, then the add doesn't demand them from its input
1166 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001167 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001168
1169 // If there is a constant on the RHS, there are a variety of xformations
1170 // we can do.
1171 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 // If null, this should be simplified elsewhere. Some of the xforms here
1173 // won't work if the RHS is zero.
1174 if (RHS->isZero())
1175 break;
1176
1177 // If the top bit of the output is demanded, demand everything from the
1178 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001179 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001180
1181 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001182 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001183 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001184 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001185
1186 // If the RHS of the add has bits set that can't affect the input, reduce
1187 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001188 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001189 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001190
1191 // Avoid excess work.
1192 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1193 break;
1194
1195 // Turn it into OR if input bits are zero.
1196 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1197 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001198 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001200 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 }
1202
1203 // We can say something about the output known-zero and known-one bits,
1204 // depending on potential carries from the input constant and the
1205 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1206 // bits set and the RHS constant is 0x01001, then we know we have a known
1207 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1208
1209 // To compute this, we first compute the potential carry bits. These are
1210 // the bits which may be modified. I'm not aware of a better way to do
1211 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001212 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001213 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001214
1215 // Now that we know which bits have carries, compute the known-1/0 sets.
1216
1217 // Bits are known one if they are known zero in one operand and one in the
1218 // other, and there is no input carry.
1219 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1220 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1221
1222 // Bits are known zero if they are known zero in both operands and there
1223 // is no input carry.
1224 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1225 } else {
1226 // If the high-bits of this ADD are not demanded, then it does not demand
1227 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001228 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001229 // Right fill the mask of bits for this ADD to demand the most
1230 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001232 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233 LHSKnownZero, LHSKnownOne, Depth+1) ||
1234 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001236 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001237 }
1238 }
1239 break;
1240 }
1241 case Instruction::Sub:
1242 // If the high-bits of this SUB are not demanded, then it does not demand
1243 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001244 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 // Right fill the mask of bits for this SUB to demand the most
1246 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001247 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001248 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001249 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1250 LHSKnownZero, LHSKnownOne, Depth+1) ||
1251 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001253 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001255 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1256 // the known zeros and ones.
1257 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 break;
1259 case Instruction::Shl:
1260 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001261 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001262 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001263 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001264 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001265 return I;
1266 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001267 RHSKnownZero <<= ShiftAmt;
1268 RHSKnownOne <<= ShiftAmt;
1269 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001270 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001271 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 }
1273 break;
1274 case Instruction::LShr:
1275 // For a logical shift right
1276 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001277 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001278
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001280 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001281 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001282 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001283 return I;
1284 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1286 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001287 if (ShiftAmt) {
1288 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001289 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001290 RHSKnownZero |= HighBits; // high bits known zero.
1291 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 }
1293 break;
1294 case Instruction::AShr:
1295 // If this is an arithmetic shift right and only the low-bit is set, we can
1296 // always convert this into a logical shr, even if the shift amount is
1297 // variable. The low bit of the shift cannot be an input sign bit unless
1298 // the shift amount is >= the size of the datatype, which is undefined.
1299 if (DemandedMask == 1) {
1300 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001301 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001302 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001303 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001304 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001305
1306 // If the sign bit is the only bit demanded by this ashr, then there is no
1307 // need to do it, the shift doesn't change the high bit.
1308 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001310
1311 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001312 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001313
Reid Spencer8cb68342007-03-12 17:25:59 +00001314 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001315 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001316 // If any of the "high bits" are demanded, we should set the sign bit as
1317 // demanded.
1318 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1319 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001320 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001322 return I;
1323 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001325 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1327 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1328
1329 // Handle the sign bits.
1330 APInt SignBit(APInt::getSignBit(BitWidth));
1331 // Adjust to where it is now in the mask.
1332 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1333
1334 // If the input sign bit is known to be zero, or if none of the top bits
1335 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001336 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001337 (HighBits & ~DemandedMask) == HighBits) {
1338 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001340 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001341 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001342 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1343 RHSKnownOne |= HighBits;
1344 }
1345 }
1346 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001347 case Instruction::SRem:
1348 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001349 APInt RA = Rem->getValue().abs();
1350 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001351 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001353
Nick Lewycky8e394322008-11-02 02:41:50 +00001354 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001355 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001356 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001357 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001359
1360 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1361 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362
1363 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001364
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001366 }
1367 }
1368 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001369 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001370 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1371 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001372 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1373 KnownZero2, KnownOne2, Depth+1) ||
1374 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001375 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001376 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001377
Chris Lattner455e9ab2009-01-21 18:09:24 +00001378 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001379 Leaders = std::max(Leaders,
1380 KnownZero2.countLeadingOnes());
1381 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001382 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001383 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001384 case Instruction::Call:
1385 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1386 switch (II->getIntrinsicID()) {
1387 default: break;
1388 case Intrinsic::bswap: {
1389 // If the only bits demanded come from one byte of the bswap result,
1390 // just shift the input byte into position to eliminate the bswap.
1391 unsigned NLZ = DemandedMask.countLeadingZeros();
1392 unsigned NTZ = DemandedMask.countTrailingZeros();
1393
1394 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1395 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1396 // have 14 leading zeros, round to 8.
1397 NLZ &= ~7;
1398 NTZ &= ~7;
1399 // If we need exactly one byte, we can do this transformation.
1400 if (BitWidth-NLZ-NTZ == 8) {
1401 unsigned ResultBit = NTZ;
1402 unsigned InputBit = BitWidth-NTZ-8;
1403
1404 // Replace this with either a left or right shift to get the byte into
1405 // the right place.
1406 Instruction *NewVal;
1407 if (InputBit > ResultBit)
1408 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001409 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001410 else
1411 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001412 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001413 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001414 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001415 }
1416
1417 // TODO: Could compute known zero/one bits based on the input.
1418 break;
1419 }
1420 }
1421 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001422 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001423 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001424 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001425
1426 // If the client is only demanding bits that we know, return the known
1427 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001428 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1429 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001430 return false;
1431}
1432
Chris Lattner867b99f2006-10-05 06:55:50 +00001433
Mon P Wangaeb06d22008-11-10 04:46:22 +00001434/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001435/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001436/// actually used by the caller. This method analyzes which elements of the
1437/// operand are undef and returns that information in UndefElts.
1438///
1439/// If the information about demanded elements can be used to simplify the
1440/// operation, the operation is simplified, then the resultant value is
1441/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001442Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1443 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001444 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001445 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001446 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001447 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001448
1449 if (isa<UndefValue>(V)) {
1450 // If the entire vector is undefined, just return this info.
1451 UndefElts = EltMask;
1452 return 0;
1453 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1454 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001455 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001456 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001457
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001459 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1460 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001461 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001462
1463 std::vector<Constant*> Elts;
1464 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001465 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001466 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001467 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001468 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1469 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001470 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001471 } else { // Otherwise, defined.
1472 Elts.push_back(CP->getOperand(i));
1473 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001474
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001476 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 return NewCP != CP ? NewCP : 0;
1478 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001479 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001480 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001481
1482 // Check if this is identity. If so, return 0 since we are not simplifying
1483 // anything.
1484 if (DemandedElts == ((1ULL << VWidth) -1))
1485 return 0;
1486
Reid Spencer9d6565a2007-02-15 02:26:10 +00001487 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001488 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001489 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001490 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001491 for (unsigned i = 0; i != VWidth; ++i) {
1492 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1493 Elts.push_back(Elt);
1494 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001495 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001496 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 }
1498
Dan Gohman488fbfc2008-09-09 18:11:14 +00001499 // Limit search depth.
1500 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001501 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001502
1503 // If multiple users are using the root value, procede with
1504 // simplification conservatively assuming that all elements
1505 // are needed.
1506 if (!V->hasOneUse()) {
1507 // Quit if we find multiple users of a non-root value though.
1508 // They'll be handled when it's their turn to be visited by
1509 // the main instcombine process.
1510 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001511 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001512 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001513
1514 // Conservatively assume that all elements are needed.
1515 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001516 }
1517
1518 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001519 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001520
1521 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001522 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 Value *TmpV;
1524 switch (I->getOpcode()) {
1525 default: break;
1526
1527 case Instruction::InsertElement: {
1528 // If this is a variable index, we don't know which element it overwrites.
1529 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001530 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001531 if (Idx == 0) {
1532 // Note that we can't propagate undef elt info, because we don't know
1533 // which elt is getting updated.
1534 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1535 UndefElts2, Depth+1);
1536 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1537 break;
1538 }
1539
1540 // If this is inserting an element that isn't demanded, remove this
1541 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001542 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001543 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1544 Worklist.Add(I);
1545 return I->getOperand(0);
1546 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001547
1548 // Otherwise, the element inserted overwrites whatever was there, so the
1549 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001550 APInt DemandedElts2 = DemandedElts;
1551 DemandedElts2.clear(IdxNo);
1552 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001553 UndefElts, Depth+1);
1554 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1555
1556 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001557 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001558 break;
1559 }
1560 case Instruction::ShuffleVector: {
1561 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001562 uint64_t LHSVWidth =
1563 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001564 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001566 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001567 unsigned MaskVal = Shuffle->getMaskValue(i);
1568 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001569 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001570 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001571 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001572 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 else
Evan Cheng388df622009-02-03 10:05:09 +00001574 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001575 }
1576 }
1577 }
1578
Nate Begeman7b254672009-02-11 22:36:25 +00001579 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001581 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1583
Nate Begeman7b254672009-02-11 22:36:25 +00001584 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1586 UndefElts3, Depth+1);
1587 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1588
1589 bool NewUndefElts = false;
1590 for (unsigned i = 0; i < VWidth; i++) {
1591 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001592 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001593 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001594 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001595 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001596 NewUndefElts = true;
1597 UndefElts.set(i);
1598 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001599 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001600 if (UndefElts3[MaskVal - LHSVWidth]) {
1601 NewUndefElts = true;
1602 UndefElts.set(i);
1603 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001604 }
1605 }
1606
1607 if (NewUndefElts) {
1608 // Add additional discovered undefs.
1609 std::vector<Constant*> Elts;
1610 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001611 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001612 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001613 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001614 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001615 Shuffle->getMaskValue(i)));
1616 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001617 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001618 MadeChange = true;
1619 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001620 break;
1621 }
Chris Lattner69878332007-04-14 22:29:23 +00001622 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001623 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001624 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1625 if (!VTy) break;
1626 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001627 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001628 unsigned Ratio;
1629
1630 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001631 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001632 // elements as are demanded of us.
1633 Ratio = 1;
1634 InputDemandedElts = DemandedElts;
1635 } else if (VWidth > InVWidth) {
1636 // Untested so far.
1637 break;
1638
1639 // If there are more elements in the result than there are in the source,
1640 // then an input element is live if any of the corresponding output
1641 // elements are live.
1642 Ratio = VWidth/InVWidth;
1643 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001644 if (DemandedElts[OutIdx])
1645 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001646 }
1647 } else {
1648 // Untested so far.
1649 break;
1650
1651 // If there are more elements in the source than there are in the result,
1652 // then an input element is live if the corresponding output element is
1653 // live.
1654 Ratio = InVWidth/VWidth;
1655 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001656 if (DemandedElts[InIdx/Ratio])
1657 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001658 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001659
Chris Lattner69878332007-04-14 22:29:23 +00001660 // div/rem demand all inputs, because they don't want divide by zero.
1661 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1662 UndefElts2, Depth+1);
1663 if (TmpV) {
1664 I->setOperand(0, TmpV);
1665 MadeChange = true;
1666 }
1667
1668 UndefElts = UndefElts2;
1669 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001670 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001671 // If there are more elements in the result than there are in the source,
1672 // then an output element is undef if the corresponding input element is
1673 // undef.
1674 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001675 if (UndefElts2[OutIdx/Ratio])
1676 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001677 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001678 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001679 // If there are more elements in the source than there are in the result,
1680 // then a result element is undef if all of the corresponding input
1681 // elements are undef.
1682 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1683 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001684 if (!UndefElts2[InIdx]) // Not undef?
1685 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001686 }
1687 break;
1688 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001689 case Instruction::And:
1690 case Instruction::Or:
1691 case Instruction::Xor:
1692 case Instruction::Add:
1693 case Instruction::Sub:
1694 case Instruction::Mul:
1695 // div/rem demand all inputs, because they don't want divide by zero.
1696 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1697 UndefElts, Depth+1);
1698 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1699 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1700 UndefElts2, Depth+1);
1701 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1702
1703 // Output elements are undefined if both are undefined. Consider things
1704 // like undef&0. The result is known zero, not undef.
1705 UndefElts &= UndefElts2;
1706 break;
1707
1708 case Instruction::Call: {
1709 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1710 if (!II) break;
1711 switch (II->getIntrinsicID()) {
1712 default: break;
1713
1714 // Binary vector operations that work column-wise. A dest element is a
1715 // function of the corresponding input elements from the two inputs.
1716 case Intrinsic::x86_sse_sub_ss:
1717 case Intrinsic::x86_sse_mul_ss:
1718 case Intrinsic::x86_sse_min_ss:
1719 case Intrinsic::x86_sse_max_ss:
1720 case Intrinsic::x86_sse2_sub_sd:
1721 case Intrinsic::x86_sse2_mul_sd:
1722 case Intrinsic::x86_sse2_min_sd:
1723 case Intrinsic::x86_sse2_max_sd:
1724 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1725 UndefElts, Depth+1);
1726 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1727 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1728 UndefElts2, Depth+1);
1729 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1730
1731 // If only the low elt is demanded and this is a scalarizable intrinsic,
1732 // scalarize it now.
1733 if (DemandedElts == 1) {
1734 switch (II->getIntrinsicID()) {
1735 default: break;
1736 case Intrinsic::x86_sse_sub_ss:
1737 case Intrinsic::x86_sse_mul_ss:
1738 case Intrinsic::x86_sse2_sub_sd:
1739 case Intrinsic::x86_sse2_mul_sd:
1740 // TODO: Lower MIN/MAX/ABS/etc
1741 Value *LHS = II->getOperand(1);
1742 Value *RHS = II->getOperand(2);
1743 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001744 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001745 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001746 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001747 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001748
1749 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001750 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001753 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001754 II->getName()), *II);
1755 break;
1756 case Intrinsic::x86_sse_mul_ss:
1757 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001758 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001759 II->getName()), *II);
1760 break;
1761 }
1762
1763 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001764 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001765 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001766 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001767 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001768 return New;
1769 }
1770 }
1771
1772 // Output elements are undefined if both are undefined. Consider things
1773 // like undef&0. The result is known zero, not undef.
1774 UndefElts &= UndefElts2;
1775 break;
1776 }
1777 break;
1778 }
1779 }
1780 return MadeChange ? I : 0;
1781}
1782
Dan Gohman45b4e482008-05-19 22:14:15 +00001783
Chris Lattner564a7272003-08-13 19:01:45 +00001784/// AssociativeOpt - Perform an optimization on an associative operator. This
1785/// function is designed to check a chain of associative operators for a
1786/// potential to apply a certain optimization. Since the optimization may be
1787/// applicable if the expression was reassociated, this checks the chain, then
1788/// reassociates the expression as necessary to expose the optimization
1789/// opportunity. This makes use of a special Functor, which must define
1790/// 'shouldApply' and 'apply' methods.
1791///
1792template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001793static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001794 unsigned Opcode = Root.getOpcode();
1795 Value *LHS = Root.getOperand(0);
1796
1797 // Quick check, see if the immediate LHS matches...
1798 if (F.shouldApply(LHS))
1799 return F.apply(Root);
1800
1801 // Otherwise, if the LHS is not of the same opcode as the root, return.
1802 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001803 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001804 // Should we apply this transform to the RHS?
1805 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1806
1807 // If not to the RHS, check to see if we should apply to the LHS...
1808 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1809 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1810 ShouldApply = true;
1811 }
1812
1813 // If the functor wants to apply the optimization to the RHS of LHSI,
1814 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1815 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001816 // Now all of the instructions are in the current basic block, go ahead
1817 // and perform the reassociation.
1818 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1819
1820 // First move the selected RHS to the LHS of the root...
1821 Root.setOperand(0, LHSI->getOperand(1));
1822
1823 // Make what used to be the LHS of the root be the user of the root...
1824 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001825 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001826 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001827 return 0;
1828 }
Chris Lattner65725312004-04-16 18:08:07 +00001829 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001830 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001831 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001832 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001833 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001834
1835 // Now propagate the ExtraOperand down the chain of instructions until we
1836 // get to LHSI.
1837 while (TmpLHSI != LHSI) {
1838 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001839 // Move the instruction to immediately before the chain we are
1840 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001841 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001842 ARI = NextLHSI;
1843
Chris Lattner564a7272003-08-13 19:01:45 +00001844 Value *NextOp = NextLHSI->getOperand(1);
1845 NextLHSI->setOperand(1, ExtraOperand);
1846 TmpLHSI = NextLHSI;
1847 ExtraOperand = NextOp;
1848 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001849
Chris Lattner564a7272003-08-13 19:01:45 +00001850 // Now that the instructions are reassociated, have the functor perform
1851 // the transformation...
1852 return F.apply(Root);
1853 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001854
Chris Lattner564a7272003-08-13 19:01:45 +00001855 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1856 }
1857 return 0;
1858}
1859
Dan Gohman844731a2008-05-13 00:00:25 +00001860namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001861
Nick Lewycky02d639f2008-05-23 04:34:58 +00001862// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001863struct AddRHS {
1864 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001865 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001866 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1867 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001868 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001869 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001870 }
1871};
1872
1873// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1874// iff C1&C2 == 0
1875struct AddMaskingAnd {
1876 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001877 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001878 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001879 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001880 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001881 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001882 }
1883 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001884 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001885 }
1886};
1887
Dan Gohman844731a2008-05-13 00:00:25 +00001888}
1889
Chris Lattner6e7ba452005-01-01 16:22:27 +00001890static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001891 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001892 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001893 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001894
Chris Lattner2eefe512004-04-09 19:05:30 +00001895 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001898
Chris Lattner2eefe512004-04-09 19:05:30 +00001899 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1900 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001901 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1902 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001903 }
1904
1905 Value *Op0 = SO, *Op1 = ConstOperand;
1906 if (!ConstIsRHS)
1907 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001908
Chris Lattner6e7ba452005-01-01 16:22:27 +00001909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001910 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1911 SO->getName()+".op");
1912 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1913 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1914 SO->getName()+".cmp");
1915 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1916 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1917 SO->getName()+".cmp");
1918 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001919}
1920
1921// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1922// constant as the other operand, try to fold the binary operator into the
1923// select arguments. This also works for Cast instructions, which obviously do
1924// not have a second operand.
1925static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1926 InstCombiner *IC) {
1927 // Don't modify shared select instructions
1928 if (!SI->hasOneUse()) return 0;
1929 Value *TV = SI->getOperand(1);
1930 Value *FV = SI->getOperand(2);
1931
1932 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001933 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001934 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001935
Chris Lattner6e7ba452005-01-01 16:22:27 +00001936 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1937 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1938
Gabor Greif051a9502008-04-06 20:25:17 +00001939 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1940 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001941 }
1942 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001943}
1944
Chris Lattner4e998b22004-09-29 05:07:12 +00001945
Chris Lattner5d1704d2009-09-27 19:57:57 +00001946/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1947/// has a PHI node as operand #0, see if we can fold the instruction into the
1948/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00001949///
1950/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1951/// that would normally be unprofitable because they strongly encourage jump
1952/// threading.
1953Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1954 bool AllowAggressive) {
1955 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00001956 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001957 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00001958 if (NumPHIValues == 0 ||
1959 // We normally only transform phis with a single use, unless we're trying
1960 // hard to make jump threading happen.
1961 (!PN->hasOneUse() && !AllowAggressive))
1962 return 0;
1963
1964
Chris Lattner5d1704d2009-09-27 19:57:57 +00001965 // Check to see if all of the operands of the PHI are simple constants
1966 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00001967 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1968 // bail out. We don't do arbitrary constant expressions here because moving
1969 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001970 BasicBlock *NonConstBB = 0;
1971 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00001972 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1973 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001974 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001975 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001976 NonConstBB = PN->getIncomingBlock(i);
1977
1978 // If the incoming non-constant value is in I's block, we have an infinite
1979 // loop.
1980 if (NonConstBB == I.getParent())
1981 return 0;
1982 }
1983
1984 // If there is exactly one non-constant value, we can insert a copy of the
1985 // operation in that block. However, if this is a critical edge, we would be
1986 // inserting the computation one some other paths (e.g. inside a loop). Only
1987 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00001988 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001989 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990 if (!BI || !BI->isUnconditional()) return 0;
1991 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001992
1993 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001994 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001995 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001996 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001997 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001998
1999 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002000 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2001 // We only currently try to fold the condition of a select when it is a phi,
2002 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002003 Value *TrueV = SI->getTrueValue();
2004 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002005 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002006 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002007 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002008 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2009 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002010 Value *InV = 0;
2011 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002012 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002013 } else {
2014 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002015 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2016 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002017 "phitmp", NonConstBB->getTerminator());
2018 Worklist.Add(cast<Instruction>(InV));
2019 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002020 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002021 }
2022 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002023 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002024 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002025 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002026 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002027 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002028 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002029 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002030 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002031 } else {
2032 assert(PN->getIncomingBlock(i) == NonConstBB);
2033 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002034 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002035 PN->getIncomingValue(i), C, "phitmp",
2036 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002037 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002038 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002039 CI->getPredicate(),
2040 PN->getIncomingValue(i), C, "phitmp",
2041 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002042 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002043 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002044
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 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002049 } else {
2050 CastInst *CI = cast<CastInst>(&I);
2051 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002052 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002053 Value *InV;
2054 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002055 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002056 } else {
2057 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002058 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002059 I.getType(), "phitmp",
2060 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002061 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002062 }
2063 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002064 }
2065 }
2066 return ReplaceInstUsesWith(I, NewPN);
2067}
2068
Chris Lattner2454a2e2008-01-29 06:52:45 +00002069
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002070/// WillNotOverflowSignedAdd - Return true if we can prove that:
2071/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2072/// This basically requires proving that the add in the original type would not
2073/// overflow to change the sign bit or have a carry out.
2074bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2075 // There are different heuristics we can use for this. Here are some simple
2076 // ones.
2077
2078 // Add has the property that adding any two 2's complement numbers can only
2079 // have one carry bit which can change a sign. As such, if LHS and RHS each
2080 // have at least two sign bits, we know that the addition of the two values will
2081 // sign extend fine.
2082 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2083 return true;
2084
2085
2086 // If one of the operands only has one non-zero bit, and if the other operand
2087 // has a known-zero bit in a more significant place than it (not including the
2088 // sign bit) the ripple may go up to and fill the zero, but won't change the
2089 // sign. For example, (X & ~4) + 1.
2090
2091 // TODO: Implement.
2092
2093 return false;
2094}
2095
Chris Lattner2454a2e2008-01-29 06:52:45 +00002096
Chris Lattner7e708292002-06-25 16:13:24 +00002097Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002098 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002099 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002100
Chris Lattner66331a42004-04-10 22:01:55 +00002101 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002102 // X + undef -> undef
2103 if (isa<UndefValue>(RHS))
2104 return ReplaceInstUsesWith(I, RHS);
2105
Chris Lattner66331a42004-04-10 22:01:55 +00002106 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002107 if (RHSC->isNullValue())
2108 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002109
Chris Lattner66331a42004-04-10 22:01:55 +00002110 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002111 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002112 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002113 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002114 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002115 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002116
2117 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2118 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002119 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002120 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002121
Eli Friedman709b33d2009-07-13 22:27:52 +00002122 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002123 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002124 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002125 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002126 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002127
2128 if (isa<PHINode>(LHS))
2129 if (Instruction *NV = FoldOpIntoPhi(I))
2130 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002131
Chris Lattner4f637d42006-01-06 17:59:59 +00002132 ConstantInt *XorRHS = 0;
2133 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002134 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002135 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002136 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002137 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002138
Zhou Sheng4351c642007-04-02 08:20:41 +00002139 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002140 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2141 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002142 do {
2143 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002144 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2145 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002146 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2147 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002148 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002149 if (!MaskedValueIsZero(XorLHS,
2150 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002151 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002152 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002153 }
2154 }
2155 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002156 C0080Val = APIntOps::lshr(C0080Val, Size);
2157 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2158 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002159
Reid Spencer35c38852007-03-28 01:36:16 +00002160 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002161 // with funny bit widths then this switch statement should be removed. It
2162 // is just here to get the size of the "middle" type back up to something
2163 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002164 const Type *MiddleType = 0;
2165 switch (Size) {
2166 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002167 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2168 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2169 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002170 }
2171 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002172 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002173 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002174 }
2175 }
Chris Lattner66331a42004-04-10 22:01:55 +00002176 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002177
Owen Anderson1d0be152009-08-13 21:58:54 +00002178 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002179 return BinaryOperator::CreateXor(LHS, RHS);
2180
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002181 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002182 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002183 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002184 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002185
2186 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2187 if (RHSI->getOpcode() == Instruction::Sub)
2188 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2189 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2190 }
2191 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2192 if (LHSI->getOpcode() == Instruction::Sub)
2193 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2194 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2195 }
Robert Bocchino71698282004-07-27 21:02:21 +00002196 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002197
Chris Lattner5c4afb92002-05-08 22:46:53 +00002198 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002199 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002200 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002201 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002202 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002203 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002204 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002205 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002206 }
2207
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002208 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002209 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002210
2211 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002212 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002213 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002214 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002215
Misha Brukmanfd939082005-04-21 23:48:37 +00002216
Chris Lattner50af16a2004-11-13 19:50:12 +00002217 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002218 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002219 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002220 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002221
2222 // X*C1 + X*C2 --> X * (C1+C2)
2223 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002224 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002225 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002226 }
2227
2228 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002229 if (dyn_castFoldableMul(RHS, C2) == LHS)
2230 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002231
Chris Lattnere617c9e2007-01-05 02:17:46 +00002232 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002233 if (dyn_castNotVal(LHS) == RHS ||
2234 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002235 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002236
Chris Lattnerad3448c2003-02-18 19:57:07 +00002237
Chris Lattner564a7272003-08-13 19:01:45 +00002238 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002239 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2240 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002241 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002242
2243 // A+B --> A|B iff A and B have no bits set in common.
2244 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2245 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2246 APInt LHSKnownOne(IT->getBitWidth(), 0);
2247 APInt LHSKnownZero(IT->getBitWidth(), 0);
2248 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2249 if (LHSKnownZero != 0) {
2250 APInt RHSKnownOne(IT->getBitWidth(), 0);
2251 APInt RHSKnownZero(IT->getBitWidth(), 0);
2252 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2253
2254 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002255 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002256 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002257 }
2258 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002259
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002260 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002261 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002262 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002263 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2264 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002265 if (W != Y) {
2266 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002267 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002268 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002269 std::swap(W, X);
2270 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002271 std::swap(Y, Z);
2272 std::swap(W, X);
2273 }
2274 }
2275
2276 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002277 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002278 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002279 }
2280 }
2281 }
2282
Chris Lattner6b032052003-10-02 15:11:26 +00002283 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002284 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002285 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002286 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002287
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002288 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002289 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002290 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002291 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002292 if (Anded == CRHS) {
2293 // See if all bits from the first bit set in the Add RHS up are included
2294 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002295 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002296
2297 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002298 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002299
2300 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002301 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002302
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002303 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2304 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002305 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002306 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002307 }
2308 }
2309 }
2310
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002311 // Try to fold constant add into select arguments.
2312 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002313 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002314 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002315 }
2316
Chris Lattner42790482007-12-20 01:56:58 +00002317 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002318 {
2319 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002320 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002321 if (!SI) {
2322 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002323 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002324 }
Chris Lattner42790482007-12-20 01:56:58 +00002325 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002326 Value *TV = SI->getTrueValue();
2327 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002328 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002329
2330 // Can we fold the add into the argument of the select?
2331 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002332 if (match(FV, m_Zero()) &&
2333 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002334 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002335 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002336 if (match(TV, m_Zero()) &&
2337 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002338 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002339 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002340 }
2341 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002342
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002343 // Check for (add (sext x), y), see if we can merge this into an
2344 // integer add followed by a sext.
2345 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2346 // (add (sext x), cst) --> (sext (add x, cst'))
2347 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2348 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002349 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002350 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002351 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002352 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2353 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002354 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2355 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002356 return new SExtInst(NewAdd, I.getType());
2357 }
2358 }
2359
2360 // (add (sext x), (sext y)) --> (sext (add int x, y))
2361 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2362 // Only do this if x/y have the same type, if at last one of them has a
2363 // single use (so we don't increase the number of sexts), and if the
2364 // integer add will not overflow.
2365 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2366 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2367 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2368 RHSConv->getOperand(0))) {
2369 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002370 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2371 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002372 return new SExtInst(NewAdd, I.getType());
2373 }
2374 }
2375 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002376
2377 return Changed ? &I : 0;
2378}
2379
2380Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2381 bool Changed = SimplifyCommutative(I);
2382 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2383
2384 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2385 // X + 0 --> X
2386 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002387 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002388 (I.getType())->getValueAPF()))
2389 return ReplaceInstUsesWith(I, LHS);
2390 }
2391
2392 if (isa<PHINode>(LHS))
2393 if (Instruction *NV = FoldOpIntoPhi(I))
2394 return NV;
2395 }
2396
2397 // -A + B --> B - A
2398 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002399 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002400 return BinaryOperator::CreateFSub(RHS, LHSV);
2401
2402 // A + -B --> A - B
2403 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002404 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002405 return BinaryOperator::CreateFSub(LHS, V);
2406
2407 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2408 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2409 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2410 return ReplaceInstUsesWith(I, LHS);
2411
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002412 // Check for (add double (sitofp x), y), see if we can merge this into an
2413 // integer add followed by a promotion.
2414 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2415 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2416 // ... if the constant fits in the integer value. This is useful for things
2417 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2418 // requires a constant pool load, and generally allows the add to be better
2419 // instcombined.
2420 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2421 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002422 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002423 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002424 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002425 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2426 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002427 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2428 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002429 return new SIToFPInst(NewAdd, I.getType());
2430 }
2431 }
2432
2433 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2434 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2435 // Only do this if x/y have the same type, if at last one of them has a
2436 // single use (so we don't increase the number of int->fp conversions),
2437 // and if the integer add will not overflow.
2438 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2439 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2440 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2441 RHSConv->getOperand(0))) {
2442 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002443 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2444 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002445 return new SIToFPInst(NewAdd, I.getType());
2446 }
2447 }
2448 }
2449
Chris Lattner7e708292002-06-25 16:13:24 +00002450 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002451}
2452
Chris Lattner7e708292002-06-25 16:13:24 +00002453Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002454 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002455
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002456 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002458
Chris Lattner233f7dc2002-08-12 21:17:25 +00002459 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002460 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002461 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002462
Chris Lattnere87597f2004-10-16 18:11:37 +00002463 if (isa<UndefValue>(Op0))
2464 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2465 if (isa<UndefValue>(Op1))
2466 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2467
Chris Lattnerd65460f2003-11-05 01:06:05 +00002468 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2469 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002470 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002471 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002472
Chris Lattnerd65460f2003-11-05 01:06:05 +00002473 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002474 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002475 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002476 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002477
Chris Lattner76b7a062007-01-15 07:02:54 +00002478 // -(X >>u 31) -> (X >>s 31)
2479 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002480 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002481 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002482 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002483 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002484 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002485 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002486 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002487 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002488 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002489 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002490 }
2491 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002492 }
2493 else if (SI->getOpcode() == Instruction::AShr) {
2494 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2495 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002496 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002497 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002498 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002499 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002500 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002501 }
2502 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002503 }
2504 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002505 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002506
2507 // Try to fold constant sub into select arguments.
2508 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002509 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002510 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002511
2512 // C - zext(bool) -> bool ? C - 1 : C
2513 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002514 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002515 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002516 }
2517
Owen Anderson1d0be152009-08-13 21:58:54 +00002518 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002519 return BinaryOperator::CreateXor(Op0, Op1);
2520
Chris Lattner43d84d62005-04-07 16:15:25 +00002521 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002522 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002523 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002524 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002525 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002526 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002527 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002528 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002529 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2530 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2531 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002532 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002533 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002534 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002535 }
2536
Chris Lattnerfd059242003-10-15 16:48:29 +00002537 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002538 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2539 // is not used by anyone else...
2540 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002541 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002542 // Swap the two operands of the subexpr...
2543 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2544 Op1I->setOperand(0, IIOp1);
2545 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002546
Chris Lattnera2881962003-02-18 19:28:33 +00002547 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002548 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002549 }
2550
2551 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2552 //
2553 if (Op1I->getOpcode() == Instruction::And &&
2554 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2555 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2556
Chris Lattner74381062009-08-30 07:44:24 +00002557 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002558 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002559 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002560
Reid Spencerac5209e2006-10-16 23:08:08 +00002561 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002562 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002563 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002564 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002565 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002566 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002567 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002568
Chris Lattnerad3448c2003-02-18 19:57:07 +00002569 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002570 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002571 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002572 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002573 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002574 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002575 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002576 }
Chris Lattner40371712002-05-09 01:29:19 +00002577 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002578 }
Chris Lattnera2881962003-02-18 19:28:33 +00002579
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002580 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2581 if (Op0I->getOpcode() == Instruction::Add) {
2582 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2583 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2584 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2585 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2586 } else if (Op0I->getOpcode() == Instruction::Sub) {
2587 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002588 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002589 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002590 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002592
Chris Lattner50af16a2004-11-13 19:50:12 +00002593 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002594 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002595 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002596 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002597
Chris Lattner50af16a2004-11-13 19:50:12 +00002598 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002599 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002600 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002601 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002602 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002603}
2604
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002605Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2606 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2607
2608 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002609 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002610 return BinaryOperator::CreateFAdd(Op0, V);
2611
2612 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2613 if (Op1I->getOpcode() == Instruction::FAdd) {
2614 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002615 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002616 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002617 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002618 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002619 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002620 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002621 }
2622
2623 return 0;
2624}
2625
Chris Lattnera0141b92007-07-15 20:42:37 +00002626/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2627/// comparison only checks the sign bit. If it only checks the sign bit, set
2628/// TrueIfSigned if the result of the comparison is true when the input value is
2629/// signed.
2630static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2631 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002632 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002633 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2634 TrueIfSigned = true;
2635 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002636 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2637 TrueIfSigned = true;
2638 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002639 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2640 TrueIfSigned = false;
2641 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002642 case ICmpInst::ICMP_UGT:
2643 // True if LHS u> RHS and RHS == high-bit-mask - 1
2644 TrueIfSigned = true;
2645 return RHS->getValue() ==
2646 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2647 case ICmpInst::ICMP_UGE:
2648 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2649 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002650 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002651 default:
2652 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002653 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002654}
2655
Chris Lattner7e708292002-06-25 16:13:24 +00002656Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002657 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002658 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002659
Eli Friedman1694e092009-07-18 09:12:15 +00002660 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002661 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002662
Chris Lattner233f7dc2002-08-12 21:17:25 +00002663 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002664 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2665 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002666
2667 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002668 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002669 if (SI->getOpcode() == Instruction::Shl)
2670 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002671 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002672 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002673
Zhou Sheng843f07672007-04-19 05:39:12 +00002674 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002675 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2676 if (CI->equalsInt(1)) // X * 1 == X
2677 return ReplaceInstUsesWith(I, Op0);
2678 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002679 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002680
Zhou Sheng97b52c22007-03-29 01:57:21 +00002681 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002682 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002683 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002684 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002685 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002686 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002687 if (Op1->isNullValue())
2688 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002689
2690 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2691 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002692 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002693
2694 // As above, vector X*splat(1.0) -> X in all defined cases.
2695 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002696 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2697 if (CI->equalsInt(1))
2698 return ReplaceInstUsesWith(I, Op0);
2699 }
2700 }
Chris Lattnera2881962003-02-18 19:28:33 +00002701 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002702
2703 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2704 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002705 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002706 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002707 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2708 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002709 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002710
2711 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002712
2713 // Try to fold constant mul into select arguments.
2714 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002715 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002716 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002717
2718 if (isa<PHINode>(Op0))
2719 if (Instruction *NV = FoldOpIntoPhi(I))
2720 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002721 }
2722
Dan Gohman186a6362009-08-12 16:04:34 +00002723 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2724 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002725 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002726
Nick Lewycky0c730792008-11-21 07:33:58 +00002727 // (X / Y) * Y = X - (X % Y)
2728 // (X / Y) * -Y = (X % Y) - X
2729 {
2730 Value *Op1 = I.getOperand(1);
2731 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2732 if (!BO ||
2733 (BO->getOpcode() != Instruction::UDiv &&
2734 BO->getOpcode() != Instruction::SDiv)) {
2735 Op1 = Op0;
2736 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2737 }
Dan Gohman186a6362009-08-12 16:04:34 +00002738 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002739 if (BO && BO->hasOneUse() &&
2740 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2741 (BO->getOpcode() == Instruction::UDiv ||
2742 BO->getOpcode() == Instruction::SDiv)) {
2743 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2744
Dan Gohmanfa94b942009-08-12 16:33:09 +00002745 // If the division is exact, X % Y is zero.
2746 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2747 if (SDiv->isExact()) {
2748 if (Op1BO == Op1)
2749 return ReplaceInstUsesWith(I, Op0BO);
2750 else
2751 return BinaryOperator::CreateNeg(Op0BO);
2752 }
2753
Chris Lattner74381062009-08-30 07:44:24 +00002754 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002755 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002756 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002757 else
Chris Lattner74381062009-08-30 07:44:24 +00002758 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002759 Rem->takeName(BO);
2760
2761 if (Op1BO == Op1)
2762 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002763 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002764 }
2765 }
2766
Owen Anderson1d0be152009-08-13 21:58:54 +00002767 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002768 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2769
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002770 // If one of the operands of the multiply is a cast from a boolean value, then
2771 // we know the bool is either zero or one, so this is a 'masking' multiply.
2772 // See if we can simplify things based on how the boolean was originally
2773 // formed.
2774 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002775 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002776 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002777 BoolCast = CI;
2778 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002779 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002780 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 BoolCast = CI;
2782 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002783 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2785 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002786 bool TIS = false;
2787
Reid Spencere4d87aa2006-12-23 06:05:41 +00002788 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002789 // multiply into a shift/and combination.
2790 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002791 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2792 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002793 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002794 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002795 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002796 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2797 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002798
2799 // If the multiply type is not the same as the source type, sign extend
2800 // or truncate to the multiply type.
Chris Lattner2345d1d2009-08-30 20:01:10 +00002801 if (I.getType() != V->getType())
2802 V = Builder->CreateIntCast(V, I.getType(), true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002803
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002804 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002805 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002806 }
2807 }
2808 }
2809
Chris Lattner7e708292002-06-25 16:13:24 +00002810 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002811}
2812
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002813Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2814 bool Changed = SimplifyCommutative(I);
2815 Value *Op0 = I.getOperand(0);
2816
2817 // Simplify mul instructions with a constant RHS...
2818 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2819 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2820 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2821 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2822 if (Op1F->isExactlyValue(1.0))
2823 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2824 } else if (isa<VectorType>(Op1->getType())) {
2825 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2826 // As above, vector X*splat(1.0) -> X in all defined cases.
2827 if (Constant *Splat = Op1V->getSplatValue()) {
2828 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2829 if (F->isExactlyValue(1.0))
2830 return ReplaceInstUsesWith(I, Op0);
2831 }
2832 }
2833 }
2834
2835 // Try to fold constant mul into select arguments.
2836 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2837 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2838 return R;
2839
2840 if (isa<PHINode>(Op0))
2841 if (Instruction *NV = FoldOpIntoPhi(I))
2842 return NV;
2843 }
2844
Dan Gohman186a6362009-08-12 16:04:34 +00002845 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2846 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002847 return BinaryOperator::CreateFMul(Op0v, Op1v);
2848
2849 return Changed ? &I : 0;
2850}
2851
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002852/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2853/// instruction.
2854bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2855 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2856
2857 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2858 int NonNullOperand = -1;
2859 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2860 if (ST->isNullValue())
2861 NonNullOperand = 2;
2862 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2863 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2864 if (ST->isNullValue())
2865 NonNullOperand = 1;
2866
2867 if (NonNullOperand == -1)
2868 return false;
2869
2870 Value *SelectCond = SI->getOperand(0);
2871
2872 // Change the div/rem to use 'Y' instead of the select.
2873 I.setOperand(1, SI->getOperand(NonNullOperand));
2874
2875 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2876 // problem. However, the select, or the condition of the select may have
2877 // multiple uses. Based on our knowledge that the operand must be non-zero,
2878 // propagate the known value for the select into other uses of it, and
2879 // propagate a known value of the condition into its other users.
2880
2881 // If the select and condition only have a single use, don't bother with this,
2882 // early exit.
2883 if (SI->use_empty() && SelectCond->hasOneUse())
2884 return true;
2885
2886 // Scan the current block backward, looking for other uses of SI.
2887 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2888
2889 while (BBI != BBFront) {
2890 --BBI;
2891 // If we found a call to a function, we can't assume it will return, so
2892 // information from below it cannot be propagated above it.
2893 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2894 break;
2895
2896 // Replace uses of the select or its condition with the known values.
2897 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2898 I != E; ++I) {
2899 if (*I == SI) {
2900 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002901 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002902 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002903 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2904 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002905 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002906 }
2907 }
2908
2909 // If we past the instruction, quit looking for it.
2910 if (&*BBI == SI)
2911 SI = 0;
2912 if (&*BBI == SelectCond)
2913 SelectCond = 0;
2914
2915 // If we ran out of things to eliminate, break out of the loop.
2916 if (SelectCond == 0 && SI == 0)
2917 break;
2918
2919 }
2920 return true;
2921}
2922
2923
Reid Spencer1628cec2006-10-26 06:15:43 +00002924/// This function implements the transforms on div instructions that work
2925/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2926/// used by the visitors to those instructions.
2927/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002928Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002930
Chris Lattner50b2ca42008-02-19 06:12:18 +00002931 // undef / X -> 0 for integer.
2932 // undef / X -> undef for FP (the undef could be a snan).
2933 if (isa<UndefValue>(Op0)) {
2934 if (Op0->getType()->isFPOrFPVector())
2935 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002936 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002937 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002938
2939 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002940 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002941 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002942
Reid Spencer1628cec2006-10-26 06:15:43 +00002943 return 0;
2944}
Misha Brukmanfd939082005-04-21 23:48:37 +00002945
Reid Spencer1628cec2006-10-26 06:15:43 +00002946/// This function implements the transforms common to both integer division
2947/// instructions (udiv and sdiv). It is called by the visitors to those integer
2948/// division instructions.
2949/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002950Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002951 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2952
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002953 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002954 if (Op0 == Op1) {
2955 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002956 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002957 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002958 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002959 }
2960
Owen Andersoneed707b2009-07-24 23:12:02 +00002961 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002962 return ReplaceInstUsesWith(I, CI);
2963 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002964
Reid Spencer1628cec2006-10-26 06:15:43 +00002965 if (Instruction *Common = commonDivTransforms(I))
2966 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002967
2968 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2969 // This does not apply for fdiv.
2970 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2971 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002972
2973 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2974 // div X, 1 == X
2975 if (RHS->equalsInt(1))
2976 return ReplaceInstUsesWith(I, Op0);
2977
2978 // (X / C1) / C2 -> X / (C1*C2)
2979 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2980 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2981 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002982 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002983 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002985 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002986 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002987 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002988 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002989
Reid Spencerbca0e382007-03-23 20:05:17 +00002990 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002991 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2992 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2993 return R;
2994 if (isa<PHINode>(Op0))
2995 if (Instruction *NV = FoldOpIntoPhi(I))
2996 return NV;
2997 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002999
Chris Lattnera2881962003-02-18 19:28:33 +00003000 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003001 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003002 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003003 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003004
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003005 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003006 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003007 return ReplaceInstUsesWith(I, Op0);
3008
Nick Lewycky895f0852008-11-27 20:21:08 +00003009 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3010 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3011 // div X, 1 == X
3012 if (X->isOne())
3013 return ReplaceInstUsesWith(I, Op0);
3014 }
3015
Reid Spencer1628cec2006-10-26 06:15:43 +00003016 return 0;
3017}
3018
3019Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3020 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3021
3022 // Handle the integer div common cases
3023 if (Instruction *Common = commonIDivTransforms(I))
3024 return Common;
3025
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003027 // X udiv C^2 -> X >> C
3028 // Check to see if this is an unsigned division with an exact power of 2,
3029 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003030 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003031 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003032 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003033
3034 // X udiv C, where C >= signbit
3035 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003036 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003037 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003038 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003039 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003040 }
3041
3042 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003043 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003044 if (RHSI->getOpcode() == Instruction::Shl &&
3045 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003046 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003047 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003048 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003049 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003050 if (uint32_t C2 = C1.logBase2())
3051 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003052 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003053 }
3054 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003055 }
3056
Reid Spencer1628cec2006-10-26 06:15:43 +00003057 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3058 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003059 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003061 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003062 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003063 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003064 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003065 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003066 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003067 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003068 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003069
3070 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003071 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003072 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003073
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003074 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003075 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003076 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003077 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003078 return 0;
3079}
3080
Reid Spencer1628cec2006-10-26 06:15:43 +00003081Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3082 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3083
3084 // Handle the integer div common cases
3085 if (Instruction *Common = commonIDivTransforms(I))
3086 return Common;
3087
3088 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3089 // sdiv X, -1 == -X
3090 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003091 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003092
Dan Gohmanfa94b942009-08-12 16:33:09 +00003093 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003094 if (cast<SDivOperator>(&I)->isExact() &&
3095 RHS->getValue().isNonNegative() &&
3096 RHS->getValue().isPowerOf2()) {
3097 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3098 RHS->getValue().exactLogBase2());
3099 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3100 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003101
3102 // -X/C --> X/-C provided the negation doesn't overflow.
3103 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3104 if (isa<Constant>(Sub->getOperand(0)) &&
3105 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003106 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003107 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3108 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003109 }
3110
3111 // If the sign bits of both operands are zero (i.e. we can prove they are
3112 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003113 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003114 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003115 if (MaskedValueIsZero(Op0, Mask)) {
3116 if (MaskedValueIsZero(Op1, Mask)) {
3117 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3118 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3119 }
3120 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003121 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003122 ShiftedInt->getValue().isPowerOf2()) {
3123 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3124 // Safe because the only negative value (1 << Y) can take on is
3125 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3126 // the sign bit set.
3127 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3128 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003129 }
Eli Friedman8be17392009-07-18 09:53:21 +00003130 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003131
3132 return 0;
3133}
3134
3135Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3136 return commonDivTransforms(I);
3137}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003138
Reid Spencer0a783f72006-11-02 01:53:59 +00003139/// This function implements the transforms on rem instructions that work
3140/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3141/// is used by the visitors to those instructions.
3142/// @brief Transforms common to all three rem instructions
3143Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003145
Chris Lattner50b2ca42008-02-19 06:12:18 +00003146 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3147 if (I.getType()->isFPOrFPVector())
3148 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003149 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003150 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003151 if (isa<UndefValue>(Op1))
3152 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003153
3154 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003155 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3156 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003157
Reid Spencer0a783f72006-11-02 01:53:59 +00003158 return 0;
3159}
3160
3161/// This function implements the transforms common to both integer remainder
3162/// instructions (urem and srem). It is called by the visitors to those integer
3163/// remainder instructions.
3164/// @brief Common integer remainder transforms
3165Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3166 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3167
3168 if (Instruction *common = commonRemTransforms(I))
3169 return common;
3170
Dale Johannesened6af242009-01-21 00:35:19 +00003171 // 0 % X == 0 for integer, we don't need to preserve faults!
3172 if (Constant *LHS = dyn_cast<Constant>(Op0))
3173 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003174 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003175
Chris Lattner857e8cd2004-12-12 21:48:58 +00003176 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003177 // X % 0 == undef, we don't need to preserve faults!
3178 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003179 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003180
Chris Lattnera2881962003-02-18 19:28:33 +00003181 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003182 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003183
Chris Lattner97943922006-02-28 05:49:21 +00003184 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3187 return R;
3188 } else if (isa<PHINode>(Op0I)) {
3189 if (Instruction *NV = FoldOpIntoPhi(I))
3190 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003191 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003192
3193 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003194 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003195 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003196 }
Chris Lattnera2881962003-02-18 19:28:33 +00003197 }
3198
Reid Spencer0a783f72006-11-02 01:53:59 +00003199 return 0;
3200}
3201
3202Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204
3205 if (Instruction *common = commonIRemTransforms(I))
3206 return common;
3207
3208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3209 // X urem C^2 -> X and C
3210 // Check to see if this is an unsigned remainder with an exact power of 2,
3211 // if so, convert to a bitwise and.
3212 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003213 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003214 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003215 }
3216
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003217 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3219 if (RHSI->getOpcode() == Instruction::Shl &&
3220 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003221 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003222 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003223 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003224 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003225 }
3226 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003227 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003228
Reid Spencer0a783f72006-11-02 01:53:59 +00003229 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3230 // where C1&C2 are powers of two.
3231 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3232 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3233 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3234 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003235 if ((STO->getValue().isPowerOf2()) &&
3236 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003237 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3238 SI->getName()+".t");
3239 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3240 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003241 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003242 }
3243 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003244 }
3245
Chris Lattner3f5b8772002-05-06 16:14:14 +00003246 return 0;
3247}
3248
Reid Spencer0a783f72006-11-02 01:53:59 +00003249Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3250 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3251
Dan Gohmancff55092007-11-05 23:16:33 +00003252 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003253 if (Instruction *Common = commonIRemTransforms(I))
3254 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003255
Dan Gohman186a6362009-08-12 16:04:34 +00003256 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003257 if (!isa<Constant>(RHSNeg) ||
3258 (isa<ConstantInt>(RHSNeg) &&
3259 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003260 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003261 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003262 I.setOperand(1, RHSNeg);
3263 return &I;
3264 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003265
Dan Gohmancff55092007-11-05 23:16:33 +00003266 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003267 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003268 if (I.getType()->isInteger()) {
3269 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3270 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3271 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003272 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003273 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003274 }
3275
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003276 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003277 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3278 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003279
Nick Lewycky9dce8732008-12-20 16:48:00 +00003280 bool hasNegative = false;
3281 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3283 if (RHS->getValue().isNegative())
3284 hasNegative = true;
3285
3286 if (hasNegative) {
3287 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003288 for (unsigned i = 0; i != VWidth; ++i) {
3289 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3290 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003291 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003292 else
3293 Elts[i] = RHS;
3294 }
3295 }
3296
Owen Andersonaf7ec972009-07-28 21:19:26 +00003297 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003298 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003299 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003300 I.setOperand(1, NewRHSV);
3301 return &I;
3302 }
3303 }
3304 }
3305
Reid Spencer0a783f72006-11-02 01:53:59 +00003306 return 0;
3307}
3308
3309Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003310 return commonRemTransforms(I);
3311}
3312
Chris Lattner457dd822004-06-09 07:59:58 +00003313// isOneBitSet - Return true if there is exactly one bit set in the specified
3314// constant.
3315static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003316 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003317}
3318
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003319// isHighOnes - Return true if the constant is of the form 1+0+.
3320// This is the same as lowones(~X).
3321static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003322 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003323}
3324
Reid Spencere4d87aa2006-12-23 06:05:41 +00003325/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003326/// are carefully arranged to allow folding of expressions such as:
3327///
3328/// (A < B) | (A > B) --> (A != B)
3329///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003330/// Note that this is only valid if the first and second predicates have the
3331/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003332///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003333/// Three bits are used to represent the condition, as follows:
3334/// 0 A > B
3335/// 1 A == B
3336/// 2 A < B
3337///
3338/// <=> Value Definition
3339/// 000 0 Always false
3340/// 001 1 A > B
3341/// 010 2 A == B
3342/// 011 3 A >= B
3343/// 100 4 A < B
3344/// 101 5 A != B
3345/// 110 6 A <= B
3346/// 111 7 Always true
3347///
3348static unsigned getICmpCode(const ICmpInst *ICI) {
3349 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003350 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003351 case ICmpInst::ICMP_UGT: return 1; // 001
3352 case ICmpInst::ICMP_SGT: return 1; // 001
3353 case ICmpInst::ICMP_EQ: return 2; // 010
3354 case ICmpInst::ICMP_UGE: return 3; // 011
3355 case ICmpInst::ICMP_SGE: return 3; // 011
3356 case ICmpInst::ICMP_ULT: return 4; // 100
3357 case ICmpInst::ICMP_SLT: return 4; // 100
3358 case ICmpInst::ICMP_NE: return 5; // 101
3359 case ICmpInst::ICMP_ULE: return 6; // 110
3360 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003361 // True -> 7
3362 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003363 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003364 return 0;
3365 }
3366}
3367
Evan Cheng8db90722008-10-14 17:15:11 +00003368/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3369/// predicate into a three bit mask. It also returns whether it is an ordered
3370/// predicate by reference.
3371static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3372 isOrdered = false;
3373 switch (CC) {
3374 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3375 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003376 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3377 case FCmpInst::FCMP_UGT: return 1; // 001
3378 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3379 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003380 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3381 case FCmpInst::FCMP_UGE: return 3; // 011
3382 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3383 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003384 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3385 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003386 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3387 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003388 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003389 default:
3390 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003391 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003392 return 0;
3393 }
3394}
3395
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396/// getICmpValue - This is the complement of getICmpCode, which turns an
3397/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003398/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003399/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003400static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003401 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003403 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003404 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003405 case 1:
3406 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003407 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003408 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003409 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3410 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003411 case 3:
3412 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003413 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003414 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003415 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003416 case 4:
3417 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003418 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003419 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003420 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3421 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003422 case 6:
3423 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003425 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003426 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003427 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003428 }
3429}
3430
Evan Cheng8db90722008-10-14 17:15:11 +00003431/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3432/// opcode and two operands into either a FCmp instruction. isordered is passed
3433/// in to determine which kind of predicate to use in the new fcmp instruction.
3434static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003435 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003436 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003437 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003438 case 0:
3439 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003440 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003441 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003442 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003443 case 1:
3444 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003445 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003446 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003448 case 2:
3449 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003450 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003451 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003452 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003453 case 3:
3454 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003455 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003456 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003457 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003458 case 4:
3459 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003460 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003461 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003462 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003463 case 5:
3464 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003465 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003466 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003467 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003468 case 6:
3469 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003470 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003471 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003472 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003473 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003474 }
3475}
3476
Chris Lattnerb9553d62008-11-16 04:55:20 +00003477/// PredicatesFoldable - Return true if both predicates match sign or if at
3478/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3480 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003481 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3482 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003483}
3484
3485namespace {
3486// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3487struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 InstCombiner &IC;
3489 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003490 ICmpInst::Predicate pred;
3491 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3492 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3493 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003495 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3496 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003497 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3498 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003499 return false;
3500 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003501 Instruction *apply(Instruction &Log) const {
3502 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3503 if (ICI->getOperand(0) != LHS) {
3504 assert(ICI->getOperand(1) == LHS);
3505 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003506 }
3507
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003508 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003509 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003510 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003511 unsigned Code;
3512 switch (Log.getOpcode()) {
3513 case Instruction::And: Code = LHSCode & RHSCode; break;
3514 case Instruction::Or: Code = LHSCode | RHSCode; break;
3515 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003516 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003517 }
3518
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003519 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3520 ICmpInst::isSignedPredicate(ICI->getPredicate());
3521
Owen Andersond672ecb2009-07-03 00:17:18 +00003522 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003523 if (Instruction *I = dyn_cast<Instruction>(RV))
3524 return I;
3525 // Otherwise, it's a constant boolean value...
3526 return IC.ReplaceInstUsesWith(Log, RV);
3527 }
3528};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003529} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003530
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003531// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3532// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003533// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003534Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003535 ConstantInt *OpRHS,
3536 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003537 BinaryOperator &TheAnd) {
3538 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003539 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003540 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003541 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003542
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 switch (Op->getOpcode()) {
3544 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003545 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003547 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003548 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003549 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 }
3551 break;
3552 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003553 if (Together == AndRHS) // (X | C) & C --> C
3554 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003555
Chris Lattner6e7ba452005-01-01 16:22:27 +00003556 if (Op->hasOneUse() && Together != OpRHS) {
3557 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003558 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003559 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003560 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003561 }
3562 break;
3563 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003564 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 // Adding a one to a single bit bit-field should be turned into an XOR
3566 // of the bit. First thing to check is to see if this AND is with a
3567 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003568 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569
3570 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003571 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003572 // Ok, at this point, we know that we are masking the result of the
3573 // ADD down to exactly one bit. If the constant we are adding has
3574 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003575 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003576
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003577 // Check to see if any bits below the one bit set in AndRHSV are set.
3578 if ((AddRHS & (AndRHSV-1)) == 0) {
3579 // If not, the only thing that can effect the output of the AND is
3580 // the bit specified by AndRHSV. If that bit is set, the effect of
3581 // the XOR is to toggle the bit. If it is clear, then the ADD has
3582 // no effect.
3583 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3584 TheAnd.setOperand(0, X);
3585 return &TheAnd;
3586 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003587 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003588 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003589 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003590 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003591 }
3592 }
3593 }
3594 }
3595 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003596
3597 case Instruction::Shl: {
3598 // We know that the AND will not produce any of the bits shifted in, so if
3599 // the anded constant includes them, clear them now!
3600 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003602 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003603 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003604 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003605
Zhou Sheng290bec52007-03-29 08:15:12 +00003606 if (CI->getValue() == ShlMask) {
3607 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003608 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3609 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003610 TheAnd.setOperand(1, CI);
3611 return &TheAnd;
3612 }
3613 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003614 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003615 case Instruction::LShr:
3616 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003617 // We know that the AND will not produce any of the bits shifted in, so if
3618 // the anded constant includes them, clear them now! This only applies to
3619 // unsigned shifts, because a signed shr may bring in set bits!
3620 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003621 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003622 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003623 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003624 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003625
Zhou Sheng290bec52007-03-29 08:15:12 +00003626 if (CI->getValue() == ShrMask) {
3627 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003628 return ReplaceInstUsesWith(TheAnd, Op);
3629 } else if (CI != AndRHS) {
3630 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3631 return &TheAnd;
3632 }
3633 break;
3634 }
3635 case Instruction::AShr:
3636 // Signed shr.
3637 // See if this is shifting in some sign extension, then masking it out
3638 // with an and.
3639 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003640 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003641 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003642 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003643 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003644 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003645 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003646 // Make the argument unsigned.
3647 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003648 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003649 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003650 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003651 }
3652 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003653 }
3654 return 0;
3655}
3656
Chris Lattner8b170942002-08-09 23:47:40 +00003657
Chris Lattnera96879a2004-09-29 17:40:11 +00003658/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003660/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3661/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003662/// insert new instructions.
3663Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 bool isSigned, bool Inside,
3665 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003666 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003667 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003668 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003669
Chris Lattnera96879a2004-09-29 17:40:11 +00003670 if (Inside) {
3671 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003672 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003673
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003675 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003676 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003677 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003678 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003679 }
3680
3681 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003682 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003683 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003684 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003685 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003686 }
3687
3688 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003689 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003690
Reid Spencere4e40032007-03-21 23:19:50 +00003691 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003692 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003693 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003694 ICmpInst::Predicate pred = (isSigned ?
3695 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003696 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003697 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003698
Reid Spencere4e40032007-03-21 23:19:50 +00003699 // Emit V-Lo >u Hi-1-Lo
3700 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003701 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003702 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003703 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003704 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003705}
3706
Chris Lattner7203e152005-09-18 07:22:02 +00003707// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3708// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3709// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3710// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003711static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003712 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003713 uint32_t BitWidth = Val->getType()->getBitWidth();
3714 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003715
3716 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003717 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003718 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003719 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003720 return true;
3721}
3722
Chris Lattner7203e152005-09-18 07:22:02 +00003723/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3724/// where isSub determines whether the operator is a sub. If we can fold one of
3725/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003726///
3727/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3728/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3729/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3730///
3731/// return (A +/- B).
3732///
3733Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003734 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003735 Instruction &I) {
3736 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3737 if (!LHSI || LHSI->getNumOperands() != 2 ||
3738 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3739
3740 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3741
3742 switch (LHSI->getOpcode()) {
3743 default: return 0;
3744 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003745 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003746 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003747 if ((Mask->getValue().countLeadingZeros() +
3748 Mask->getValue().countPopulation()) ==
3749 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003750 break;
3751
3752 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3753 // part, we don't need any explicit masks to take them out of A. If that
3754 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003755 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003756 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003757 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003758 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003759 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003760 break;
3761 }
3762 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003763 return 0;
3764 case Instruction::Or:
3765 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003766 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003767 if ((Mask->getValue().countLeadingZeros() +
3768 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003769 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003770 break;
3771 return 0;
3772 }
3773
Chris Lattnerc8e77562005-09-18 04:24:45 +00003774 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003775 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3776 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003777}
3778
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003779/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3780Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3781 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003782 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003783 ConstantInt *LHSCst, *RHSCst;
3784 ICmpInst::Predicate LHSCC, RHSCC;
3785
Chris Lattnerea065fb2008-11-16 05:10:52 +00003786 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003787 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003788 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003789 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003790 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003791 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003792
3793 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3794 // where C is a power of 2
3795 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3796 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003797 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003798 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003799 }
3800
3801 // From here on, we only handle:
3802 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3803 if (Val != Val2) return 0;
3804
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003805 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3806 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3807 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3808 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3809 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3810 return 0;
3811
3812 // We can't fold (ugt x, C) & (sgt x, C2).
3813 if (!PredicatesFoldable(LHSCC, RHSCC))
3814 return 0;
3815
3816 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003817 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003818 if (ICmpInst::isSignedPredicate(LHSCC) ||
3819 (ICmpInst::isEquality(LHSCC) &&
3820 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003821 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003823 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3824
3825 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003826 std::swap(LHS, RHS);
3827 std::swap(LHSCst, RHSCst);
3828 std::swap(LHSCC, RHSCC);
3829 }
3830
3831 // At this point, we know we have have two icmp instructions
3832 // comparing a value against two constants and and'ing the result
3833 // together. Because of the above check, we know that we only have
3834 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3835 // (from the FoldICmpLogical check above), that the two constants
3836 // are not equal and that the larger constant is on the RHS
3837 assert(LHSCst != RHSCst && "Compares not folded above?");
3838
3839 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003840 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 case ICmpInst::ICMP_EQ:
3842 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003843 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003844 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3845 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3846 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003847 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003848 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3849 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3850 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3851 return ReplaceInstUsesWith(I, LHS);
3852 }
3853 case ICmpInst::ICMP_NE:
3854 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003855 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003856 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003857 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003858 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 break; // (X != 13 & X u< 15) -> no change
3860 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003861 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003862 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003863 break; // (X != 13 & X s< 15) -> no change
3864 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3865 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3866 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3867 return ReplaceInstUsesWith(I, RHS);
3868 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003869 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003870 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003871 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003872 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003873 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 }
3875 break; // (X != 13 & X != 15) -> no change
3876 }
3877 break;
3878 case ICmpInst::ICMP_ULT:
3879 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003880 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3882 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003883 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003884 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3885 break;
3886 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3887 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3888 return ReplaceInstUsesWith(I, LHS);
3889 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3890 break;
3891 }
3892 break;
3893 case ICmpInst::ICMP_SLT:
3894 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003895 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3897 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003898 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003899 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3900 break;
3901 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3902 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3903 return ReplaceInstUsesWith(I, LHS);
3904 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3905 break;
3906 }
3907 break;
3908 case ICmpInst::ICMP_UGT:
3909 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003910 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003911 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3912 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3913 return ReplaceInstUsesWith(I, RHS);
3914 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3915 break;
3916 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003917 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003918 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003919 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003920 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003921 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003922 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003923 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3924 break;
3925 }
3926 break;
3927 case ICmpInst::ICMP_SGT:
3928 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003929 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003930 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3931 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3932 return ReplaceInstUsesWith(I, RHS);
3933 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3934 break;
3935 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003936 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003937 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003938 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003939 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003940 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003941 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003942 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3943 break;
3944 }
3945 break;
3946 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003947
3948 return 0;
3949}
3950
Chris Lattner42d1be02009-07-23 05:14:02 +00003951Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3952 FCmpInst *RHS) {
3953
3954 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3955 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3956 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3957 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3958 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3959 // If either of the constants are nans, then the whole thing returns
3960 // false.
3961 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003962 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003963 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003964 LHS->getOperand(0), RHS->getOperand(0));
3965 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003966
3967 // Handle vector zeros. This occurs because the canonical form of
3968 // "fcmp ord x,x" is "fcmp ord x, 0".
3969 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3970 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003971 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003972 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003973 return 0;
3974 }
3975
3976 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3977 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3978 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3979
3980
3981 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3982 // Swap RHS operands to match LHS.
3983 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3984 std::swap(Op1LHS, Op1RHS);
3985 }
3986
3987 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3988 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3989 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003990 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003991
3992 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003993 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003994 if (Op0CC == FCmpInst::FCMP_TRUE)
3995 return ReplaceInstUsesWith(I, RHS);
3996 if (Op1CC == FCmpInst::FCMP_TRUE)
3997 return ReplaceInstUsesWith(I, LHS);
3998
3999 bool Op0Ordered;
4000 bool Op1Ordered;
4001 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4002 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4003 if (Op1Pred == 0) {
4004 std::swap(LHS, RHS);
4005 std::swap(Op0Pred, Op1Pred);
4006 std::swap(Op0Ordered, Op1Ordered);
4007 }
4008 if (Op0Pred == 0) {
4009 // uno && ueq -> uno && (uno || eq) -> ueq
4010 // ord && olt -> ord && (ord && lt) -> olt
4011 if (Op0Ordered == Op1Ordered)
4012 return ReplaceInstUsesWith(I, RHS);
4013
4014 // uno && oeq -> uno && (ord && eq) -> false
4015 // uno && ord -> false
4016 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004017 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004018 // ord && ueq -> ord && (uno || eq) -> oeq
4019 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4020 Op0LHS, Op0RHS, Context));
4021 }
4022 }
4023
4024 return 0;
4025}
4026
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004027
Chris Lattner7e708292002-06-25 16:13:24 +00004028Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004029 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004030 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004031
Chris Lattnere87597f2004-10-16 18:11:37 +00004032 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004034
Chris Lattner6e7ba452005-01-01 16:22:27 +00004035 // and X, X = X
4036 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004037 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004038
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004039 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004040 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004041 if (SimplifyDemandedInstructionBits(I))
4042 return &I;
4043 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004044 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004045 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004046 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004047 } else if (isa<ConstantAggregateZero>(Op1)) {
4048 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004049 }
4050 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004051
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004052 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004053 const APInt& AndRHSMask = AndRHS->getValue();
4054 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004055
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004056 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004057 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004058 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004059 Value *Op0LHS = Op0I->getOperand(0);
4060 Value *Op0RHS = Op0I->getOperand(1);
4061 switch (Op0I->getOpcode()) {
4062 case Instruction::Xor:
4063 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004064 // If the mask is only needed on one incoming arm, push it up.
4065 if (Op0I->hasOneUse()) {
4066 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4067 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004068 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4069 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004070 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004071 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004072 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004073 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004074 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4075 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004076 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4077 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004078 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004079 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4080 }
4081 }
4082
Chris Lattner6e7ba452005-01-01 16:22:27 +00004083 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004084 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004085 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4086 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4088 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004089 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004090 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004091 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004092 break;
4093
4094 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004095 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4096 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4098 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004099 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004100
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004101 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4102 // has 1's for all bits that the subtraction with A might affect.
4103 if (Op0I->hasOneUse()) {
4104 uint32_t BitWidth = AndRHSMask.getBitWidth();
4105 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4106 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4107
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004108 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004109 if (!(A && A->isZero()) && // avoid infinite recursion.
4110 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004111 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004112 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4113 }
4114 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004115 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004116
4117 case Instruction::Shl:
4118 case Instruction::LShr:
4119 // (1 << x) & 1 --> zext(x == 0)
4120 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004121 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004122 Value *NewICmp =
4123 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004124 return new ZExtInst(NewICmp, I.getType());
4125 }
4126 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004127 }
4128
Chris Lattner58403262003-07-23 19:25:52 +00004129 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004130 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004131 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004132 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004133 // If this is an integer truncation or change from signed-to-unsigned, and
4134 // if the source is an and/or with immediate, transform it. This
4135 // frequently occurs for bitfield accesses.
4136 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004137 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004138 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004139 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004140 if (CastOp->getOpcode() == Instruction::And) {
4141 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004142 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4143 // This will fold the two constants together, which may allow
4144 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004145 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004146 CastOp->getOperand(0), I.getType(),
4147 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004148 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004149 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004150 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004151 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004152 } else if (CastOp->getOpcode() == Instruction::Or) {
4153 // Change: and (cast (or X, C1) to T), C2
4154 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004155 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004156 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004157 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004158 return ReplaceInstUsesWith(I, AndRHS);
4159 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004160 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004161 }
Chris Lattner06782f82003-07-23 19:36:21 +00004162 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004163
4164 // Try to fold constant and into select arguments.
4165 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004166 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004167 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004168 if (isa<PHINode>(Op0))
4169 if (Instruction *NV = FoldOpIntoPhi(I))
4170 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004171 }
4172
Dan Gohman186a6362009-08-12 16:04:34 +00004173 Value *Op0NotVal = dyn_castNotVal(Op0);
4174 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004175
Chris Lattner5b62aa72004-06-18 06:07:51 +00004176 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004177 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004178
Misha Brukmancb6267b2004-07-30 12:50:08 +00004179 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004180 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004181 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4182 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004183 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004184 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004185
4186 {
Chris Lattner003b6202007-06-15 05:58:24 +00004187 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004188 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004189 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4190 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004191
4192 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004193 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004195 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004196 }
4197 }
4198
Dan Gohman4ae51262009-08-12 16:23:25 +00004199 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004200 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4201 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004202
4203 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004204 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004205 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004206 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004207 }
4208 }
Chris Lattner64daab52006-04-01 08:03:55 +00004209
4210 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004211 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004212 if (A == Op1) { // (A^B)&A -> A&(A^B)
4213 I.swapOperands(); // Simplify below
4214 std::swap(Op0, Op1);
4215 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4216 cast<BinaryOperator>(Op0)->swapOperands();
4217 I.swapOperands(); // Simplify below
4218 std::swap(Op0, Op1);
4219 }
4220 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004221
Chris Lattner64daab52006-04-01 08:03:55 +00004222 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004223 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004224 if (B == Op0) { // B&(A^B) -> B&(B^A)
4225 cast<BinaryOperator>(Op1)->swapOperands();
4226 std::swap(A, B);
4227 }
Chris Lattner74381062009-08-30 07:44:24 +00004228 if (A == Op0) // A&(A^B) -> A & ~B
4229 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004230 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004231
4232 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004233 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4234 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004235 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004236 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4237 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004238 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004239 }
4240
Reid Spencere4d87aa2006-12-23 06:05:41 +00004241 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4242 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004243 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004244 return R;
4245
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004246 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4247 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4248 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004249 }
4250
Chris Lattner6fc205f2006-05-05 06:39:07 +00004251 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004252 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4253 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4254 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4255 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004256 if (SrcTy == Op1C->getOperand(0)->getType() &&
4257 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004258 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004259 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4260 I.getType(), TD) &&
4261 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4262 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004263 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4264 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004265 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004266 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004267 }
Chris Lattnere511b742006-11-14 07:46:50 +00004268
4269 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004270 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4271 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4272 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004273 SI0->getOperand(1) == SI1->getOperand(1) &&
4274 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004275 Value *NewOp =
4276 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4277 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004278 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004279 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004280 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004281 }
4282
Evan Cheng8db90722008-10-14 17:15:11 +00004283 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004284 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004285 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4286 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4287 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004288 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004289
Chris Lattner7e708292002-06-25 16:13:24 +00004290 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004291}
4292
Chris Lattner8c34cd22008-10-05 02:13:19 +00004293/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4294/// capable of providing pieces of a bswap. The subexpression provides pieces
4295/// of a bswap if it is proven that each of the non-zero bytes in the output of
4296/// the expression came from the corresponding "byte swapped" byte in some other
4297/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4298/// we know that the expression deposits the low byte of %X into the high byte
4299/// of the bswap result and that all other bytes are zero. This expression is
4300/// accepted, the high byte of ByteValues is set to X to indicate a correct
4301/// match.
4302///
4303/// This function returns true if the match was unsuccessful and false if so.
4304/// On entry to the function the "OverallLeftShift" is a signed integer value
4305/// indicating the number of bytes that the subexpression is later shifted. For
4306/// example, if the expression is later right shifted by 16 bits, the
4307/// OverallLeftShift value would be -2 on entry. This is used to specify which
4308/// byte of ByteValues is actually being set.
4309///
4310/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4311/// byte is masked to zero by a user. For example, in (X & 255), X will be
4312/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4313/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4314/// always in the local (OverallLeftShift) coordinate space.
4315///
4316static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4317 SmallVector<Value*, 8> &ByteValues) {
4318 if (Instruction *I = dyn_cast<Instruction>(V)) {
4319 // If this is an or instruction, it may be an inner node of the bswap.
4320 if (I->getOpcode() == Instruction::Or) {
4321 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4322 ByteValues) ||
4323 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4324 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004325 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004326
4327 // If this is a logical shift by a constant multiple of 8, recurse with
4328 // OverallLeftShift and ByteMask adjusted.
4329 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4330 unsigned ShAmt =
4331 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4332 // Ensure the shift amount is defined and of a byte value.
4333 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4334 return true;
4335
4336 unsigned ByteShift = ShAmt >> 3;
4337 if (I->getOpcode() == Instruction::Shl) {
4338 // X << 2 -> collect(X, +2)
4339 OverallLeftShift += ByteShift;
4340 ByteMask >>= ByteShift;
4341 } else {
4342 // X >>u 2 -> collect(X, -2)
4343 OverallLeftShift -= ByteShift;
4344 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004345 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004346 }
4347
4348 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4349 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4350
4351 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4352 ByteValues);
4353 }
4354
4355 // If this is a logical 'and' with a mask that clears bytes, clear the
4356 // corresponding bytes in ByteMask.
4357 if (I->getOpcode() == Instruction::And &&
4358 isa<ConstantInt>(I->getOperand(1))) {
4359 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4360 unsigned NumBytes = ByteValues.size();
4361 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4362 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4363
4364 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4365 // If this byte is masked out by a later operation, we don't care what
4366 // the and mask is.
4367 if ((ByteMask & (1 << i)) == 0)
4368 continue;
4369
4370 // If the AndMask is all zeros for this byte, clear the bit.
4371 APInt MaskB = AndMask & Byte;
4372 if (MaskB == 0) {
4373 ByteMask &= ~(1U << i);
4374 continue;
4375 }
4376
4377 // If the AndMask is not all ones for this byte, it's not a bytezap.
4378 if (MaskB != Byte)
4379 return true;
4380
4381 // Otherwise, this byte is kept.
4382 }
4383
4384 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4385 ByteValues);
4386 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004387 }
4388
Chris Lattner8c34cd22008-10-05 02:13:19 +00004389 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4390 // the input value to the bswap. Some observations: 1) if more than one byte
4391 // is demanded from this input, then it could not be successfully assembled
4392 // into a byteswap. At least one of the two bytes would not be aligned with
4393 // their ultimate destination.
4394 if (!isPowerOf2_32(ByteMask)) return true;
4395 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004396
Chris Lattner8c34cd22008-10-05 02:13:19 +00004397 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4398 // is demanded, it needs to go into byte 0 of the result. This means that the
4399 // byte needs to be shifted until it lands in the right byte bucket. The
4400 // shift amount depends on the position: if the byte is coming from the high
4401 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4402 // low part, it must be shifted left.
4403 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4404 if (InputByteNo < ByteValues.size()/2) {
4405 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4406 return true;
4407 } else {
4408 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4409 return true;
4410 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004411
4412 // If the destination byte value is already defined, the values are or'd
4413 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004414 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004415 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004416 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004417 return false;
4418}
4419
4420/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4421/// If so, insert the new bswap intrinsic and return it.
4422Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004423 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004424 if (!ITy || ITy->getBitWidth() % 16 ||
4425 // ByteMask only allows up to 32-byte values.
4426 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004427 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428
4429 /// ByteValues - For each byte of the result, we keep track of which value
4430 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004431 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004432 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004433
4434 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004435 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4436 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004437 return 0;
4438
4439 // Check to see if all of the bytes come from the same value.
4440 Value *V = ByteValues[0];
4441 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4442
4443 // Check to make sure that all of the bytes come from the same value.
4444 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4445 if (ByteValues[i] != V)
4446 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004447 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004448 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004449 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004450 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004451}
4452
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004453/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4454/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4455/// we can simplify this expression to "cond ? C : D or B".
4456static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004457 Value *C, Value *D,
4458 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004459 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004460 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004461 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004462 return 0;
4463
Chris Lattnera6a474d2008-11-16 04:26:55 +00004464 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004465 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004466 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004467 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004468 return SelectInst::Create(Cond, C, B);
4469 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004470 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004471 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004472 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004473 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004474 return 0;
4475}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004476
Chris Lattner69d4ced2008-11-16 05:20:07 +00004477/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4478Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4479 ICmpInst *LHS, ICmpInst *RHS) {
4480 Value *Val, *Val2;
4481 ConstantInt *LHSCst, *RHSCst;
4482 ICmpInst::Predicate LHSCC, RHSCC;
4483
4484 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004485 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004486 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004487 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004488 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004489 return 0;
4490
4491 // From here on, we only handle:
4492 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4493 if (Val != Val2) return 0;
4494
4495 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4496 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4497 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4498 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4499 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4500 return 0;
4501
4502 // We can't fold (ugt x, C) | (sgt x, C2).
4503 if (!PredicatesFoldable(LHSCC, RHSCC))
4504 return 0;
4505
4506 // Ensure that the larger constant is on the RHS.
4507 bool ShouldSwap;
4508 if (ICmpInst::isSignedPredicate(LHSCC) ||
4509 (ICmpInst::isEquality(LHSCC) &&
4510 ICmpInst::isSignedPredicate(RHSCC)))
4511 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4512 else
4513 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4514
4515 if (ShouldSwap) {
4516 std::swap(LHS, RHS);
4517 std::swap(LHSCst, RHSCst);
4518 std::swap(LHSCC, RHSCC);
4519 }
4520
4521 // At this point, we know we have have two icmp instructions
4522 // comparing a value against two constants and or'ing the result
4523 // together. Because of the above check, we know that we only have
4524 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4525 // FoldICmpLogical check above), that the two constants are not
4526 // equal.
4527 assert(LHSCst != RHSCst && "Compares not folded above?");
4528
4529 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004530 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004531 case ICmpInst::ICMP_EQ:
4532 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004533 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004534 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004535 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004536 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004537 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004538 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004539 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004540 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004541 }
4542 break; // (X == 13 | X == 15) -> no change
4543 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4544 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4545 break;
4546 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4547 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4548 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4549 return ReplaceInstUsesWith(I, RHS);
4550 }
4551 break;
4552 case ICmpInst::ICMP_NE:
4553 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004554 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004555 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4556 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4557 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4558 return ReplaceInstUsesWith(I, LHS);
4559 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4560 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4561 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004562 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004563 }
4564 break;
4565 case ICmpInst::ICMP_ULT:
4566 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004567 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004568 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4569 break;
4570 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4571 // If RHSCst is [us]MAXINT, it is always false. Not handling
4572 // this can cause overflow.
4573 if (RHSCst->isMaxValue(false))
4574 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004575 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004576 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004577 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4578 break;
4579 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4580 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4581 return ReplaceInstUsesWith(I, RHS);
4582 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4583 break;
4584 }
4585 break;
4586 case ICmpInst::ICMP_SLT:
4587 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004588 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004589 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4590 break;
4591 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4592 // If RHSCst is [us]MAXINT, it is always false. Not handling
4593 // this can cause overflow.
4594 if (RHSCst->isMaxValue(true))
4595 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004596 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004597 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004598 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4599 break;
4600 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4601 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4602 return ReplaceInstUsesWith(I, RHS);
4603 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4604 break;
4605 }
4606 break;
4607 case ICmpInst::ICMP_UGT:
4608 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004609 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4611 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4612 return ReplaceInstUsesWith(I, LHS);
4613 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4614 break;
4615 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4616 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004617 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004618 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4619 break;
4620 }
4621 break;
4622 case ICmpInst::ICMP_SGT:
4623 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004624 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4626 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4627 return ReplaceInstUsesWith(I, LHS);
4628 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4629 break;
4630 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4631 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004632 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004633 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4634 break;
4635 }
4636 break;
4637 }
4638 return 0;
4639}
4640
Chris Lattner5414cc52009-07-23 05:46:22 +00004641Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4642 FCmpInst *RHS) {
4643 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4644 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4645 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4646 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4647 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4648 // If either of the constants are nans, then the whole thing returns
4649 // true.
4650 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004651 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004652
4653 // Otherwise, no need to compare the two constants, compare the
4654 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004655 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004656 LHS->getOperand(0), RHS->getOperand(0));
4657 }
4658
4659 // Handle vector zeros. This occurs because the canonical form of
4660 // "fcmp uno x,x" is "fcmp uno x, 0".
4661 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4662 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004663 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004664 LHS->getOperand(0), RHS->getOperand(0));
4665
4666 return 0;
4667 }
4668
4669 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4670 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4671 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4672
4673 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4674 // Swap RHS operands to match LHS.
4675 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4676 std::swap(Op1LHS, Op1RHS);
4677 }
4678 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4679 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4680 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004681 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004682 Op0LHS, Op0RHS);
4683 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004684 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004685 if (Op0CC == FCmpInst::FCMP_FALSE)
4686 return ReplaceInstUsesWith(I, RHS);
4687 if (Op1CC == FCmpInst::FCMP_FALSE)
4688 return ReplaceInstUsesWith(I, LHS);
4689 bool Op0Ordered;
4690 bool Op1Ordered;
4691 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4692 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4693 if (Op0Ordered == Op1Ordered) {
4694 // If both are ordered or unordered, return a new fcmp with
4695 // or'ed predicates.
4696 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4697 Op0LHS, Op0RHS, Context);
4698 if (Instruction *I = dyn_cast<Instruction>(RV))
4699 return I;
4700 // Otherwise, it's a constant boolean value...
4701 return ReplaceInstUsesWith(I, RV);
4702 }
4703 }
4704 return 0;
4705}
4706
Bill Wendlinga698a472008-12-01 08:23:25 +00004707/// FoldOrWithConstants - This helper function folds:
4708///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004709/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004710///
4711/// into:
4712///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004713/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004714///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004715/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004716Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004717 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004718 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4719 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004720
Bill Wendling286a0542008-12-02 06:24:20 +00004721 Value *V1 = 0;
4722 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004723 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004724
Bill Wendling29976b92008-12-02 06:18:11 +00004725 APInt Xor = CI1->getValue() ^ CI2->getValue();
4726 if (!Xor.isAllOnesValue()) return 0;
4727
Bill Wendling286a0542008-12-02 06:24:20 +00004728 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004729 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004730 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004731 }
4732
4733 return 0;
4734}
4735
Chris Lattner7e708292002-06-25 16:13:24 +00004736Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004737 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004738 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004739
Chris Lattner42593e62007-03-24 23:56:43 +00004740 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004741 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004742
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004743 // or X, X = X
4744 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004745 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004746
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004747 // See if we can simplify any instructions used by the instruction whose sole
4748 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004749 if (SimplifyDemandedInstructionBits(I))
4750 return &I;
4751 if (isa<VectorType>(I.getType())) {
4752 if (isa<ConstantAggregateZero>(Op1)) {
4753 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4754 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4755 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4756 return ReplaceInstUsesWith(I, I.getOperand(1));
4757 }
Chris Lattner42593e62007-03-24 23:56:43 +00004758 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004759
Chris Lattner3f5b8772002-05-06 16:14:14 +00004760 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004761 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004762 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004763 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004764 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004765 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004766 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004767 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004768 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004769 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004770 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004771
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004772 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004773 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004774 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004775 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004776 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004777 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004778 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004779 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004780
4781 // Try to fold constant and into select arguments.
4782 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004783 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004784 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004785 if (isa<PHINode>(Op0))
4786 if (Instruction *NV = FoldOpIntoPhi(I))
4787 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004788 }
4789
Chris Lattner4f637d42006-01-06 17:59:59 +00004790 Value *A = 0, *B = 0;
4791 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004792
Dan Gohman4ae51262009-08-12 16:23:25 +00004793 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004794 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4795 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004796 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004797 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4798 return ReplaceInstUsesWith(I, Op0);
4799
Chris Lattner6423d4c2006-07-10 20:25:24 +00004800 // (A | B) | C and A | (B | C) -> bswap if possible.
4801 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004802 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4803 match(Op1, m_Or(m_Value(), m_Value())) ||
4804 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4805 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004806 if (Instruction *BSwap = MatchBSwap(I))
4807 return BSwap;
4808 }
4809
Chris Lattner6e4c6492005-05-09 04:58:36 +00004810 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004811 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004812 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004813 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004814 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004815 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004816 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004817 }
4818
4819 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004820 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004821 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004822 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004823 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004824 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004825 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004826 }
4827
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004828 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004829 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004830 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4831 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004832 Value *V1 = 0, *V2 = 0, *V3 = 0;
4833 C1 = dyn_cast<ConstantInt>(C);
4834 C2 = dyn_cast<ConstantInt>(D);
4835 if (C1 && C2) { // (A & C1)|(B & C2)
4836 // If we have: ((V + N) & C1) | (V & C2)
4837 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4838 // replace with V+N.
4839 if (C1->getValue() == ~C2->getValue()) {
4840 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004842 // Add commutes, try both ways.
4843 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4844 return ReplaceInstUsesWith(I, A);
4845 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4846 return ReplaceInstUsesWith(I, A);
4847 }
4848 // Or commutes, try both ways.
4849 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004850 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004851 // Add commutes, try both ways.
4852 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4853 return ReplaceInstUsesWith(I, B);
4854 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4855 return ReplaceInstUsesWith(I, B);
4856 }
4857 }
Chris Lattner044e5332007-04-08 08:01:49 +00004858 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004859 }
4860
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004861 // Check to see if we have any common things being and'ed. If so, find the
4862 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004863 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4864 if (A == B) // (A & C)|(A & D) == A & (C|D)
4865 V1 = A, V2 = C, V3 = D;
4866 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4867 V1 = A, V2 = B, V3 = C;
4868 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4869 V1 = C, V2 = A, V3 = D;
4870 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4871 V1 = C, V2 = A, V3 = B;
4872
4873 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004874 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004875 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004876 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004877 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004878
Dan Gohman1975d032008-10-30 20:40:10 +00004879 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004880 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004881 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004882 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004883 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004884 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004885 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004886 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004887 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004888
Bill Wendlingb01865c2008-11-30 13:52:49 +00004889 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004890 if ((match(C, m_Not(m_Specific(D))) &&
4891 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004892 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004893 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004894 if ((match(A, m_Not(m_Specific(D))) &&
4895 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004896 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004897 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004898 if ((match(C, m_Not(m_Specific(B))) &&
4899 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004900 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004901 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004902 if ((match(A, m_Not(m_Specific(B))) &&
4903 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004904 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004905 }
Chris Lattnere511b742006-11-14 07:46:50 +00004906
4907 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004908 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4909 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4910 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004911 SI0->getOperand(1) == SI1->getOperand(1) &&
4912 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004913 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4914 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004915 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004916 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004917 }
4918 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004919
Bill Wendlingb3833d12008-12-01 01:07:11 +00004920 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004921 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4922 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004923 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004924 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004925 }
4926 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004927 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4928 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004929 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004930 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004931 }
4932
Dan Gohman4ae51262009-08-12 16:23:25 +00004933 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004934 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004935 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004936 } else {
4937 A = 0;
4938 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004939 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004940 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004941 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004942 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004943
Misha Brukmancb6267b2004-07-30 12:50:08 +00004944 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004945 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004946 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004947 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004948 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004949 }
Chris Lattnera2881962003-02-18 19:28:33 +00004950
Reid Spencere4d87aa2006-12-23 06:05:41 +00004951 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4952 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004953 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004954 return R;
4955
Chris Lattner69d4ced2008-11-16 05:20:07 +00004956 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4957 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4958 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004959 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004960
4961 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004962 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004963 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004964 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004965 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4966 !isa<ICmpInst>(Op1C->getOperand(0))) {
4967 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004968 if (SrcTy == Op1C->getOperand(0)->getType() &&
4969 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004970 // Only do this if the casts both really cause code to be
4971 // generated.
4972 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4973 I.getType(), TD) &&
4974 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4975 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004976 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4977 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004978 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004979 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004980 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004981 }
Chris Lattner99c65742007-10-24 05:38:08 +00004982 }
4983
4984
4985 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4986 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004987 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4988 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4989 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004990 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004991
Chris Lattner7e708292002-06-25 16:13:24 +00004992 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004993}
4994
Dan Gohman844731a2008-05-13 00:00:25 +00004995namespace {
4996
Chris Lattnerc317d392004-02-16 01:20:27 +00004997// XorSelf - Implements: X ^ X --> 0
4998struct XorSelf {
4999 Value *RHS;
5000 XorSelf(Value *rhs) : RHS(rhs) {}
5001 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5002 Instruction *apply(BinaryOperator &Xor) const {
5003 return &Xor;
5004 }
5005};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005006
Dan Gohman844731a2008-05-13 00:00:25 +00005007}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005008
Chris Lattner7e708292002-06-25 16:13:24 +00005009Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005010 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005011 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005012
Evan Chengd34af782008-03-25 20:07:13 +00005013 if (isa<UndefValue>(Op1)) {
5014 if (isa<UndefValue>(Op0))
5015 // Handle undef ^ undef -> 0 special case. This is a common
5016 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005017 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005018 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005019 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005020
Chris Lattnerc317d392004-02-16 01:20:27 +00005021 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005022 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005023 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005024 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005025 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005026
5027 // See if we can simplify any instructions used by the instruction whose sole
5028 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005029 if (SimplifyDemandedInstructionBits(I))
5030 return &I;
5031 if (isa<VectorType>(I.getType()))
5032 if (isa<ConstantAggregateZero>(Op1))
5033 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005034
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005035 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005036 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005037 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5038 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5039 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5040 if (Op0I->getOpcode() == Instruction::And ||
5041 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005042 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5043 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005044 Value *NotY =
5045 Builder->CreateNot(Op0I->getOperand(1),
5046 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005047 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005048 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005049 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005050 }
5051 }
5052 }
5053 }
5054
5055
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005056 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005057 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005058 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005059 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005060 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005061 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005062
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005063 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005064 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005065 FCI->getOperand(0), FCI->getOperand(1));
5066 }
5067
Nick Lewycky517e1f52008-05-31 19:01:33 +00005068 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5069 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5070 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5071 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5072 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005073 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5074 (RHS == ConstantExpr::getCast(Opcode,
5075 ConstantInt::getTrue(*Context),
5076 Op0C->getDestTy()))) {
5077 CI->setPredicate(CI->getInversePredicate());
5078 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005079 }
5080 }
5081 }
5082 }
5083
Reid Spencere4d87aa2006-12-23 06:05:41 +00005084 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005085 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005086 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5087 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005088 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5089 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005090 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005091 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005092 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005093
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005094 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005095 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005096 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005097 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005098 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005099 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005100 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005101 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005102 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005103 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005104 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005105 Constant *C = ConstantInt::get(*Context,
5106 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005107 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005108
Chris Lattner7c4049c2004-01-12 19:35:11 +00005109 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005110 } else if (Op0I->getOpcode() == Instruction::Or) {
5111 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005112 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005113 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005114 // Anything in both C1 and C2 is known to be zero, remove it from
5115 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005116 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5117 NewRHS = ConstantExpr::getAnd(NewRHS,
5118 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005119 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005120 I.setOperand(0, Op0I->getOperand(0));
5121 I.setOperand(1, NewRHS);
5122 return &I;
5123 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005124 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005125 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005126 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005127
5128 // Try to fold constant and into select arguments.
5129 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005130 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005131 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005132 if (isa<PHINode>(Op0))
5133 if (Instruction *NV = FoldOpIntoPhi(I))
5134 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005135 }
5136
Dan Gohman186a6362009-08-12 16:04:34 +00005137 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005138 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005139 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005140
Dan Gohman186a6362009-08-12 16:04:34 +00005141 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005142 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005143 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005144
Chris Lattner318bf792007-03-18 22:51:34 +00005145
5146 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5147 if (Op1I) {
5148 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005149 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005150 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005151 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005152 I.swapOperands();
5153 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005154 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005155 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005156 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005157 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005158 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005159 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005160 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005161 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005162 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005163 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005164 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005165 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005166 std::swap(A, B);
5167 }
Chris Lattner318bf792007-03-18 22:51:34 +00005168 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005169 I.swapOperands(); // Simplified below.
5170 std::swap(Op0, Op1);
5171 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005172 }
Chris Lattner318bf792007-03-18 22:51:34 +00005173 }
5174
5175 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5176 if (Op0I) {
5177 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005178 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005180 if (A == Op1) // (B|A)^B == (A|B)^B
5181 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005182 if (B == Op1) // (A|B)^B == A & ~B
5183 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005184 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005185 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005186 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005187 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005188 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005189 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005190 if (A == Op1) // (A&B)^A -> (B&A)^A
5191 std::swap(A, B);
5192 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005193 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005194 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005195 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005196 }
Chris Lattner318bf792007-03-18 22:51:34 +00005197 }
5198
5199 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5200 if (Op0I && Op1I && Op0I->isShift() &&
5201 Op0I->getOpcode() == Op1I->getOpcode() &&
5202 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5203 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005204 Value *NewOp =
5205 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5206 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005207 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005208 Op1I->getOperand(1));
5209 }
5210
5211 if (Op0I && Op1I) {
5212 Value *A, *B, *C, *D;
5213 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005214 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5215 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005216 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005217 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005218 }
5219 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005220 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5221 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005222 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005223 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005224 }
5225
5226 // (A & B)^(C & D)
5227 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005228 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5229 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005230 // (X & Y)^(X & Y) -> (Y^Z) & X
5231 Value *X = 0, *Y = 0, *Z = 0;
5232 if (A == C)
5233 X = A, Y = B, Z = D;
5234 else if (A == D)
5235 X = A, Y = B, Z = C;
5236 else if (B == C)
5237 X = B, Y = A, Z = D;
5238 else if (B == D)
5239 X = B, Y = A, Z = C;
5240
5241 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005242 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005243 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005244 }
5245 }
5246 }
5247
Reid Spencere4d87aa2006-12-23 06:05:41 +00005248 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5249 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005250 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005251 return R;
5252
Chris Lattner6fc205f2006-05-05 06:39:07 +00005253 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005254 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005255 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005256 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5257 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005258 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005259 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005260 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5261 I.getType(), TD) &&
5262 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5263 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005264 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5265 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005266 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005267 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005268 }
Chris Lattner99c65742007-10-24 05:38:08 +00005269 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005270
Chris Lattner7e708292002-06-25 16:13:24 +00005271 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005272}
5273
Owen Andersond672ecb2009-07-03 00:17:18 +00005274static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005275 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005276 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005277}
Chris Lattnera96879a2004-09-29 17:40:11 +00005278
Dan Gohman6de29f82009-06-15 22:12:54 +00005279static bool HasAddOverflow(ConstantInt *Result,
5280 ConstantInt *In1, ConstantInt *In2,
5281 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005282 if (IsSigned)
5283 if (In2->getValue().isNegative())
5284 return Result->getValue().sgt(In1->getValue());
5285 else
5286 return Result->getValue().slt(In1->getValue());
5287 else
5288 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005289}
5290
Dan Gohman6de29f82009-06-15 22:12:54 +00005291/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005292/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005293static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005294 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005295 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005296 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005297
Dan Gohman6de29f82009-06-15 22:12:54 +00005298 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5299 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005300 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005301 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5302 ExtractElement(In1, Idx, Context),
5303 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005304 IsSigned))
5305 return true;
5306 }
5307 return false;
5308 }
5309
5310 return HasAddOverflow(cast<ConstantInt>(Result),
5311 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5312 IsSigned);
5313}
5314
5315static bool HasSubOverflow(ConstantInt *Result,
5316 ConstantInt *In1, ConstantInt *In2,
5317 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005318 if (IsSigned)
5319 if (In2->getValue().isNegative())
5320 return Result->getValue().slt(In1->getValue());
5321 else
5322 return Result->getValue().sgt(In1->getValue());
5323 else
5324 return Result->getValue().ugt(In1->getValue());
5325}
5326
Dan Gohman6de29f82009-06-15 22:12:54 +00005327/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5328/// overflowed for this type.
5329static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005330 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005331 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005332 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005333
5334 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5335 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005336 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005337 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5338 ExtractElement(In1, Idx, Context),
5339 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005340 IsSigned))
5341 return true;
5342 }
5343 return false;
5344 }
5345
5346 return HasSubOverflow(cast<ConstantInt>(Result),
5347 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5348 IsSigned);
5349}
5350
Chris Lattner574da9b2005-01-13 20:14:25 +00005351/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5352/// code necessary to compute the offset from the base pointer (without adding
5353/// in the base pointer). Return the result as a signed integer of intptr size.
5354static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005355 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005356 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005357 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005358 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005359
5360 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005361 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005362 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005363
Gabor Greif177dd3f2008-06-12 21:37:33 +00005364 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5365 ++i, ++GTI) {
5366 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005367 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005368 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5369 if (OpC->isZero()) continue;
5370
5371 // Handle a struct index, which adds its field offset to the pointer.
5372 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5373 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5374
Chris Lattner74381062009-08-30 07:44:24 +00005375 Result = IC.Builder->CreateAdd(Result,
5376 ConstantInt::get(IntPtrTy, Size),
5377 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005378 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005379 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005380
Owen Andersoneed707b2009-07-24 23:12:02 +00005381 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005382 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005383 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5384 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005385 // Emit an add instruction.
5386 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005387 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005388 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005389 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005390 if (Op->getType() != IntPtrTy)
5391 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005392 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005393 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005394 // We'll let instcombine(mul) convert this to a shl if possible.
5395 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005396 }
5397
5398 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005399 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005400 }
5401 return Result;
5402}
5403
Chris Lattner10c0d912008-04-22 02:53:33 +00005404
Dan Gohman8f080f02009-07-17 22:16:21 +00005405/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5406/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5407/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5408/// be complex, and scales are involved. The above expression would also be
5409/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5410/// This later form is less amenable to optimization though, and we are allowed
5411/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005412///
5413/// If we can't emit an optimized form for this expression, this returns null.
5414///
5415static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5416 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005417 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005418 gep_type_iterator GTI = gep_type_begin(GEP);
5419
5420 // Check to see if this gep only has a single variable index. If so, and if
5421 // any constant indices are a multiple of its scale, then we can compute this
5422 // in terms of the scale of the variable index. For example, if the GEP
5423 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5424 // because the expression will cross zero at the same point.
5425 unsigned i, e = GEP->getNumOperands();
5426 int64_t Offset = 0;
5427 for (i = 1; i != e; ++i, ++GTI) {
5428 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5429 // Compute the aggregate offset of constant indices.
5430 if (CI->isZero()) continue;
5431
5432 // Handle a struct index, which adds its field offset to the pointer.
5433 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5434 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5435 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005436 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005437 Offset += Size*CI->getSExtValue();
5438 }
5439 } else {
5440 // Found our variable index.
5441 break;
5442 }
5443 }
5444
5445 // If there are no variable indices, we must have a constant offset, just
5446 // evaluate it the general way.
5447 if (i == e) return 0;
5448
5449 Value *VariableIdx = GEP->getOperand(i);
5450 // Determine the scale factor of the variable element. For example, this is
5451 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005452 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005453
5454 // Verify that there are no other variable indices. If so, emit the hard way.
5455 for (++i, ++GTI; i != e; ++i, ++GTI) {
5456 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5457 if (!CI) return 0;
5458
5459 // Compute the aggregate offset of constant indices.
5460 if (CI->isZero()) continue;
5461
5462 // Handle a struct index, which adds its field offset to the pointer.
5463 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5464 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005466 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005467 Offset += Size*CI->getSExtValue();
5468 }
5469 }
5470
5471 // Okay, we know we have a single variable index, which must be a
5472 // pointer/array/vector index. If there is no offset, life is simple, return
5473 // the index.
5474 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5475 if (Offset == 0) {
5476 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5477 // we don't need to bother extending: the extension won't affect where the
5478 // computation crosses zero.
5479 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005480 VariableIdx = new TruncInst(VariableIdx,
5481 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005482 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005483 return VariableIdx;
5484 }
5485
5486 // Otherwise, there is an index. The computation we will do will be modulo
5487 // the pointer size, so get it.
5488 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5489
5490 Offset &= PtrSizeMask;
5491 VariableScale &= PtrSizeMask;
5492
5493 // To do this transformation, any constant index must be a multiple of the
5494 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5495 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5496 // multiple of the variable scale.
5497 int64_t NewOffs = Offset / (int64_t)VariableScale;
5498 if (Offset != NewOffs*(int64_t)VariableScale)
5499 return 0;
5500
5501 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005502 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005503 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005504 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005505 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005506 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005507 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005508 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005509}
5510
5511
Reid Spencere4d87aa2006-12-23 06:05:41 +00005512/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005513/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005514Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005515 ICmpInst::Predicate Cond,
5516 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005517 // Look through bitcasts.
5518 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5519 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005520
Chris Lattner574da9b2005-01-13 20:14:25 +00005521 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005522 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005523 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005524 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005525 // know pointers can't overflow since the gep is inbounds. See if we can
5526 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005527 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5528
5529 // If not, synthesize the offset the hard way.
5530 if (Offset == 0)
5531 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005532 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005533 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005534 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005535 // If the base pointers are different, but the indices are the same, just
5536 // compare the base pointer.
5537 if (PtrBase != GEPRHS->getOperand(0)) {
5538 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005539 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005540 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005541 if (IndicesTheSame)
5542 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5543 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5544 IndicesTheSame = false;
5545 break;
5546 }
5547
5548 // If all indices are the same, just compare the base pointers.
5549 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005550 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005551 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005552
5553 // Otherwise, the base pointers are different and the indices are
5554 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005555 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005556 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005557
Chris Lattnere9d782b2005-01-13 22:25:21 +00005558 // If one of the GEPs has all zero indices, recurse.
5559 bool AllZeros = true;
5560 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5561 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5562 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5563 AllZeros = false;
5564 break;
5565 }
5566 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005567 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5568 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005569
5570 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005571 AllZeros = true;
5572 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5573 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5574 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5575 AllZeros = false;
5576 break;
5577 }
5578 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005579 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005580
Chris Lattner4401c9c2005-01-14 00:20:05 +00005581 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5582 // If the GEPs only differ by one index, compare it.
5583 unsigned NumDifferences = 0; // Keep track of # differences.
5584 unsigned DiffOperand = 0; // The operand that differs.
5585 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5586 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005587 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5588 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005589 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005590 NumDifferences = 2;
5591 break;
5592 } else {
5593 if (NumDifferences++) break;
5594 DiffOperand = i;
5595 }
5596 }
5597
5598 if (NumDifferences == 0) // SAME GEP?
5599 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005600 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005601 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005602
Chris Lattner4401c9c2005-01-14 00:20:05 +00005603 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005604 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5605 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005606 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005607 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005608 }
5609 }
5610
Reid Spencere4d87aa2006-12-23 06:05:41 +00005611 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005612 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005613 if (TD &&
5614 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005615 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5616 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5617 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5618 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005619 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005620 }
5621 }
5622 return 0;
5623}
5624
Chris Lattnera5406232008-05-19 20:18:56 +00005625/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5626///
5627Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5628 Instruction *LHSI,
5629 Constant *RHSC) {
5630 if (!isa<ConstantFP>(RHSC)) return 0;
5631 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5632
5633 // Get the width of the mantissa. We don't want to hack on conversions that
5634 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005635 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005636 if (MantissaWidth == -1) return 0; // Unknown.
5637
5638 // Check to see that the input is converted from an integer type that is small
5639 // enough that preserves all bits. TODO: check here for "known" sign bits.
5640 // 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 +00005641 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005642
5643 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005644 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5645 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005646 ++InputSize;
5647
5648 // If the conversion would lose info, don't hack on this.
5649 if ((int)InputSize > MantissaWidth)
5650 return 0;
5651
5652 // Otherwise, we can potentially simplify the comparison. We know that it
5653 // will always come through as an integer value and we know the constant is
5654 // not a NAN (it would have been previously simplified).
5655 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5656
5657 ICmpInst::Predicate Pred;
5658 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005659 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005660 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005661 case FCmpInst::FCMP_OEQ:
5662 Pred = ICmpInst::ICMP_EQ;
5663 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005664 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005665 case FCmpInst::FCMP_OGT:
5666 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5667 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005668 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005669 case FCmpInst::FCMP_OGE:
5670 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5671 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005672 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005673 case FCmpInst::FCMP_OLT:
5674 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5675 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005676 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005677 case FCmpInst::FCMP_OLE:
5678 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5679 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005680 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005681 case FCmpInst::FCMP_ONE:
5682 Pred = ICmpInst::ICMP_NE;
5683 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005684 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005685 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005686 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005687 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005688 }
5689
5690 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5691
5692 // Now we know that the APFloat is a normal number, zero or inf.
5693
Chris Lattner85162782008-05-20 03:50:52 +00005694 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005695 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005696 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005697
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 if (!LHSUnsigned) {
5699 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5700 // and large values.
5701 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5702 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5703 APFloat::rmNearestTiesToEven);
5704 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5705 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5706 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005707 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5708 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005709 }
5710 } else {
5711 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5712 // +INF and large values.
5713 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5714 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5715 APFloat::rmNearestTiesToEven);
5716 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5717 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5718 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005719 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5720 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005721 }
Chris Lattnera5406232008-05-19 20:18:56 +00005722 }
5723
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005724 if (!LHSUnsigned) {
5725 // See if the RHS value is < SignedMin.
5726 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5727 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5728 APFloat::rmNearestTiesToEven);
5729 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5730 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5731 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005732 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5733 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005734 }
Chris Lattnera5406232008-05-19 20:18:56 +00005735 }
5736
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005737 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5738 // [0, UMAX], but it may still be fractional. See if it is fractional by
5739 // casting the FP value to the integer value and back, checking for equality.
5740 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005741 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005742 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5743 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005744 if (!RHS.isZero()) {
5745 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005746 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5747 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005748 if (!Equal) {
5749 // If we had a comparison against a fractional value, we have to adjust
5750 // the compare predicate and sometimes the value. RHSC is rounded towards
5751 // zero at this point.
5752 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005753 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005754 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005755 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005756 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005757 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005758 case ICmpInst::ICMP_ULE:
5759 // (float)int <= 4.4 --> int <= 4
5760 // (float)int <= -4.4 --> false
5761 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005762 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005763 break;
5764 case ICmpInst::ICMP_SLE:
5765 // (float)int <= 4.4 --> int <= 4
5766 // (float)int <= -4.4 --> int < -4
5767 if (RHS.isNegative())
5768 Pred = ICmpInst::ICMP_SLT;
5769 break;
5770 case ICmpInst::ICMP_ULT:
5771 // (float)int < -4.4 --> false
5772 // (float)int < 4.4 --> int <= 4
5773 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005774 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005775 Pred = ICmpInst::ICMP_ULE;
5776 break;
5777 case ICmpInst::ICMP_SLT:
5778 // (float)int < -4.4 --> int < -4
5779 // (float)int < 4.4 --> int <= 4
5780 if (!RHS.isNegative())
5781 Pred = ICmpInst::ICMP_SLE;
5782 break;
5783 case ICmpInst::ICMP_UGT:
5784 // (float)int > 4.4 --> int > 4
5785 // (float)int > -4.4 --> true
5786 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005787 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005788 break;
5789 case ICmpInst::ICMP_SGT:
5790 // (float)int > 4.4 --> int > 4
5791 // (float)int > -4.4 --> int >= -4
5792 if (RHS.isNegative())
5793 Pred = ICmpInst::ICMP_SGE;
5794 break;
5795 case ICmpInst::ICMP_UGE:
5796 // (float)int >= -4.4 --> true
5797 // (float)int >= 4.4 --> int > 4
5798 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005799 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005800 Pred = ICmpInst::ICMP_UGT;
5801 break;
5802 case ICmpInst::ICMP_SGE:
5803 // (float)int >= -4.4 --> int >= -4
5804 // (float)int >= 4.4 --> int > 4
5805 if (!RHS.isNegative())
5806 Pred = ICmpInst::ICMP_SGT;
5807 break;
5808 }
Chris Lattnera5406232008-05-19 20:18:56 +00005809 }
5810 }
5811
5812 // Lower this FP comparison into an appropriate integer version of the
5813 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005814 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005815}
5816
Reid Spencere4d87aa2006-12-23 06:05:41 +00005817Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5818 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005819 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005820
Chris Lattner58e97462007-01-14 19:42:17 +00005821 // Fold trivial predicates.
5822 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005823 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005824 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Chris Lattner9e17b632009-09-02 05:12:37 +00005825 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005826
5827 // Simplify 'fcmp pred X, X'
5828 if (Op0 == Op1) {
5829 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005830 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005831 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5832 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5833 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Chris Lattner9e17b632009-09-02 05:12:37 +00005834 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
Chris Lattner58e97462007-01-14 19:42:17 +00005835 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5836 case FCmpInst::FCMP_OLT: // True if ordered and less than
5837 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Chris Lattner9e17b632009-09-02 05:12:37 +00005838 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
Chris Lattner58e97462007-01-14 19:42:17 +00005839
5840 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5841 case FCmpInst::FCMP_ULT: // True if unordered or less than
5842 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5843 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5844 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5845 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005846 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005847 return &I;
5848
5849 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5850 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5851 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5852 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5853 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5854 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005855 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005856 return &I;
5857 }
5858 }
5859
Reid Spencere4d87aa2006-12-23 06:05:41 +00005860 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005861 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005862
Reid Spencere4d87aa2006-12-23 06:05:41 +00005863 // Handle fcmp with constant RHS
5864 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005865 // If the constant is a nan, see if we can fold the comparison based on it.
5866 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5867 if (CFP->getValueAPF().isNaN()) {
5868 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005869 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005870 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5871 "Comparison must be either ordered or unordered!");
5872 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005873 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005874 }
5875 }
5876
Reid Spencere4d87aa2006-12-23 06:05:41 +00005877 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5878 switch (LHSI->getOpcode()) {
5879 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005880 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5881 // block. If in the same block, we're encouraging jump threading. If
5882 // not, we are just pessimizing the code by making an i1 phi.
5883 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00005884 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005885 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005887 case Instruction::SIToFP:
5888 case Instruction::UIToFP:
5889 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5890 return NV;
5891 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 case Instruction::Select:
5893 // If either operand of the select is a constant, we can fold the
5894 // comparison into the select arms, which will cause one to be
5895 // constant folded and the select turned into a bitwise or.
5896 Value *Op1 = 0, *Op2 = 0;
5897 if (LHSI->hasOneUse()) {
5898 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5899 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005900 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005901 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005902 Op2 = Builder->CreateFCmp(I.getPredicate(),
5903 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005904 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5905 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005906 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005907 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005908 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5909 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005910 }
5911 }
5912
5913 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005914 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005915 break;
5916 }
5917 }
5918
5919 return Changed ? &I : 0;
5920}
5921
5922Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5923 bool Changed = SimplifyCompare(I);
5924 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5925 const Type *Ty = Op0->getType();
5926
5927 // icmp X, X
5928 if (Op0 == Op1)
Chris Lattner9e17b632009-09-02 05:12:37 +00005929 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005930 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005931
5932 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Chris Lattner9e17b632009-09-02 05:12:37 +00005933 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005934
Reid Spencere4d87aa2006-12-23 06:05:41 +00005935 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005936 // addresses never equal each other! We already know that Op0 != Op1.
Victor Hernandez83d63912009-09-18 22:35:49 +00005937 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
Misha Brukmanfd939082005-04-21 23:48:37 +00005938 isa<ConstantPointerNull>(Op0)) &&
Victor Hernandez83d63912009-09-18 22:35:49 +00005939 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005940 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005941 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005942 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005943
Reid Spencere4d87aa2006-12-23 06:05:41 +00005944 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005945 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005946 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005947 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005948 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005949 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005950 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005951 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005952 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005953 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005954
Reid Spencere4d87aa2006-12-23 06:05:41 +00005955 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005956 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005957 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005958 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005959 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005960 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005961 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005962 case ICmpInst::ICMP_SGT:
5963 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005964 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005965 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005966 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005967 return BinaryOperator::CreateAnd(Not, Op0);
5968 }
5969 case ICmpInst::ICMP_UGE:
5970 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5971 // FALL THROUGH
5972 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005973 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005974 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005975 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005976 case ICmpInst::ICMP_SGE:
5977 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5978 // FALL THROUGH
5979 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005980 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005981 return BinaryOperator::CreateOr(Not, Op0);
5982 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005983 }
Chris Lattner8b170942002-08-09 23:47:40 +00005984 }
5985
Dan Gohman1c8491e2009-04-25 17:12:48 +00005986 unsigned BitWidth = 0;
5987 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005988 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5989 else if (Ty->isIntOrIntVector())
5990 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005991
5992 bool isSignBit = false;
5993
Dan Gohman81b28ce2008-09-16 18:46:06 +00005994 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005995 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005996 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005997
Chris Lattnerb6566012008-01-05 01:18:20 +00005998 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5999 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006000 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006001 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006002 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006003 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006004
Dan Gohman81b28ce2008-09-16 18:46:06 +00006005 // If we have an icmp le or icmp ge instruction, turn it into the
6006 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6007 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00006008 switch (I.getPredicate()) {
6009 default: break;
6010 case ICmpInst::ICMP_ULE:
6011 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006012 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006013 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006014 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006015 case ICmpInst::ICMP_SLE:
6016 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006017 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006018 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006019 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006020 case ICmpInst::ICMP_UGE:
6021 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006022 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006023 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006024 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006025 case ICmpInst::ICMP_SGE:
6026 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006027 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006028 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006029 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006030 }
6031
Chris Lattner183661e2008-07-11 05:40:05 +00006032 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006033 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006034 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006035 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6036 }
6037
6038 // See if we can fold the comparison based on range information we can get
6039 // by checking whether bits are known to be zero or one in the input.
6040 if (BitWidth != 0) {
6041 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6042 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6043
6044 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006045 isSignBit ? APInt::getSignBit(BitWidth)
6046 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006047 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006048 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 if (SimplifyDemandedBits(I.getOperandUse(1),
6050 APInt::getAllOnesValue(BitWidth),
6051 Op1KnownZero, Op1KnownOne, 0))
6052 return &I;
6053
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006054 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006055 // in. Compute the Min, Max and RHS values based on the known bits. For the
6056 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006057 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6058 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6059 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6060 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6061 Op0Min, Op0Max);
6062 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6063 Op1Min, Op1Max);
6064 } else {
6065 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6066 Op0Min, Op0Max);
6067 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6068 Op1Min, Op1Max);
6069 }
6070
Chris Lattner183661e2008-07-11 05:40:05 +00006071 // If Min and Max are known to be the same, then SimplifyDemandedBits
6072 // figured out that the LHS is a constant. Just constant fold this now so
6073 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006075 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006076 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006077 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006078 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006079 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006080
Chris Lattner183661e2008-07-11 05:40:05 +00006081 // Based on the range information we know about the LHS, see if we can
6082 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006083 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006084 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006085 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006087 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006088 break;
6089 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006092 break;
6093 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006095 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006097 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006098 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006099 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6101 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006102 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006103 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006104
6105 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6106 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006107 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006108 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006109 }
Chris Lattner84dff672008-07-11 05:08:55 +00006110 break;
6111 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006113 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006115 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006116
6117 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006118 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6120 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006121 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006122 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123
6124 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6125 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006126 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006127 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 }
Chris Lattner84dff672008-07-11 05:08:55 +00006129 break;
6130 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006131 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006132 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006134 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006135 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006136 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6138 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006139 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006140 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 }
Chris Lattner84dff672008-07-11 05:08:55 +00006142 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006143 case ICmpInst::ICMP_SGT:
6144 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006145 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006147 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148
6149 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006150 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006151 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6152 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006153 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006154 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 }
6156 break;
6157 case ICmpInst::ICMP_SGE:
6158 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6159 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006161 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006162 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163 break;
6164 case ICmpInst::ICMP_SLE:
6165 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6166 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006167 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006168 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006169 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006170 break;
6171 case ICmpInst::ICMP_UGE:
6172 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6173 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006174 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006175 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006176 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006177 break;
6178 case ICmpInst::ICMP_ULE:
6179 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6180 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006181 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006182 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006183 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006184 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006185 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006186
6187 // Turn a signed comparison into an unsigned one if both operands
6188 // are known to have the same sign.
6189 if (I.isSignedPredicate() &&
6190 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6191 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006192 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006193 }
6194
6195 // Test if the ICmpInst instruction is used exclusively by a select as
6196 // part of a minimum or maximum operation. If so, refrain from doing
6197 // any other folding. This helps out other analyses which understand
6198 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6199 // and CodeGen. And in this case, at least one of the comparison
6200 // operands has at least one user besides the compare (the select),
6201 // which would often largely negate the benefit of folding anyway.
6202 if (I.hasOneUse())
6203 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6204 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6205 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6206 return 0;
6207
6208 // See if we are doing a comparison between a constant and an instruction that
6209 // can be folded into the comparison.
6210 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006211 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006212 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006213 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006214 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006215 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6216 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006217 }
6218
Chris Lattner01deb9d2007-04-03 17:43:25 +00006219 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006220 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6221 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6222 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006223 case Instruction::GetElementPtr:
6224 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006225 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006226 bool isAllZeros = true;
6227 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6228 if (!isa<Constant>(LHSI->getOperand(i)) ||
6229 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6230 isAllZeros = false;
6231 break;
6232 }
6233 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006234 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006235 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006236 }
6237 break;
6238
Chris Lattner6970b662005-04-23 15:31:55 +00006239 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006240 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006241 // block. If in the same block, we're encouraging jump threading. If
6242 // not, we are just pessimizing the code by making an i1 phi.
6243 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006244 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006245 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006246 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006247 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006248 // If either operand of the select is a constant, we can fold the
6249 // comparison into the select arms, which will cause one to be
6250 // constant folded and the select turned into a bitwise or.
6251 Value *Op1 = 0, *Op2 = 0;
6252 if (LHSI->hasOneUse()) {
6253 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6254 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006255 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006256 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006257 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6258 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006259 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6260 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006261 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006263 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6264 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006265 }
6266 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006267
Chris Lattner6970b662005-04-23 15:31:55 +00006268 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006269 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006270 break;
6271 }
Chris Lattner4802d902007-04-06 18:57:34 +00006272 case Instruction::Malloc:
6273 // If we have (malloc != null), and if the malloc has a single use, we
6274 // can assume it is successful and remove the malloc.
6275 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006276 Worklist.Add(LHSI);
Victor Hernandez83d63912009-09-18 22:35:49 +00006277 return ReplaceInstUsesWith(I,
6278 ConstantInt::get(Type::getInt1Ty(*Context),
6279 !I.isTrueWhenEqual()));
6280 }
6281 break;
6282 case Instruction::Call:
6283 // If we have (malloc != null), and if the malloc has a single use, we
6284 // can assume it is successful and remove the malloc.
6285 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6286 isa<ConstantPointerNull>(RHSC)) {
6287 Worklist.Add(LHSI);
6288 return ReplaceInstUsesWith(I,
6289 ConstantInt::get(Type::getInt1Ty(*Context),
6290 !I.isTrueWhenEqual()));
6291 }
6292 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006293 }
Chris Lattner6970b662005-04-23 15:31:55 +00006294 }
6295
Reid Spencere4d87aa2006-12-23 06:05:41 +00006296 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006297 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006298 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006299 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006300 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006301 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6302 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006303 return NI;
6304
Reid Spencere4d87aa2006-12-23 06:05:41 +00006305 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006306 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6307 // now.
6308 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6309 if (isa<PointerType>(Op0->getType()) &&
6310 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006311 // We keep moving the cast from the left operand over to the right
6312 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006313 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006314
Chris Lattner57d86372007-01-06 01:45:59 +00006315 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6316 // so eliminate it as well.
6317 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6318 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006319
Chris Lattnerde90b762003-11-03 04:25:02 +00006320 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006321 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006322 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006323 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006324 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006325 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006326 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006327 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006328 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006329 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006330 }
Chris Lattner57d86372007-01-06 01:45:59 +00006331 }
6332
6333 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006334 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006335 // This comes up when you have code like
6336 // int X = A < B;
6337 // if (X) ...
6338 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006339 // with a constant or another cast from the same type.
6340 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006341 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006342 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006343 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006344
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006345 // See if it's the same type of instruction on the left and right.
6346 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6347 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006348 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006349 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006350 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006351 default: break;
6352 case Instruction::Add:
6353 case Instruction::Sub:
6354 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006355 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006356 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006357 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006358 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6359 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6360 if (CI->getValue().isSignBit()) {
6361 ICmpInst::Predicate Pred = I.isSignedPredicate()
6362 ? I.getUnsignedPredicate()
6363 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006364 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006365 Op1I->getOperand(0));
6366 }
6367
6368 if (CI->getValue().isMaxSignedValue()) {
6369 ICmpInst::Predicate Pred = I.isSignedPredicate()
6370 ? I.getUnsignedPredicate()
6371 : I.getSignedPredicate();
6372 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006373 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006374 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006375 }
6376 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006377 break;
6378 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006379 if (!I.isEquality())
6380 break;
6381
Nick Lewycky5d52c452008-08-21 05:56:10 +00006382 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6383 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6384 // Mask = -1 >> count-trailing-zeros(Cst).
6385 if (!CI->isZero() && !CI->isOne()) {
6386 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006387 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006388 APInt::getLowBitsSet(AP.getBitWidth(),
6389 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006390 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006391 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6392 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006393 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006394 }
6395 }
6396 break;
6397 }
6398 }
6399 }
6400 }
6401
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006402 // ~x < ~y --> y < x
6403 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006404 if (match(Op0, m_Not(m_Value(A))) &&
6405 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006406 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006407 }
6408
Chris Lattner65b72ba2006-09-18 04:22:48 +00006409 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006410 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006411
6412 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006413 if (match(Op0, m_Neg(m_Value(A))) &&
6414 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006415 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006416
Dan Gohman4ae51262009-08-12 16:23:25 +00006417 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006418 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6419 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006420 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006421 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006422 }
6423
Dan Gohman4ae51262009-08-12 16:23:25 +00006424 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006425 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006426 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006427 if (match(B, m_ConstantInt(C1)) &&
6428 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006429 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006430 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006431 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6432 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006433 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006434
6435 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006436 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6437 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6438 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6439 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006440 }
6441 }
6442
Dan Gohman4ae51262009-08-12 16:23:25 +00006443 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006444 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006445 // A == (A^B) -> B == 0
6446 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006447 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006448 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006449 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006450
6451 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006452 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006453 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006454 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006455
6456 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006457 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006458 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006459 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006460
Chris Lattner9c2328e2006-11-14 06:06:06 +00006461 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6462 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006463 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6464 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006465 Value *X = 0, *Y = 0, *Z = 0;
6466
6467 if (A == C) {
6468 X = B; Y = D; Z = A;
6469 } else if (A == D) {
6470 X = B; Y = C; Z = A;
6471 } else if (B == C) {
6472 X = A; Y = D; Z = B;
6473 } else if (B == D) {
6474 X = A; Y = C; Z = B;
6475 }
6476
6477 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006478 Op1 = Builder->CreateXor(X, Y, "tmp");
6479 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006480 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006481 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006482 return &I;
6483 }
6484 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006485 }
Chris Lattner7e708292002-06-25 16:13:24 +00006486 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006487}
6488
Chris Lattner562ef782007-06-20 23:46:26 +00006489
6490/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6491/// and CmpRHS are both known to be integer constants.
6492Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6493 ConstantInt *DivRHS) {
6494 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6495 const APInt &CmpRHSV = CmpRHS->getValue();
6496
6497 // FIXME: If the operand types don't match the type of the divide
6498 // then don't attempt this transform. The code below doesn't have the
6499 // logic to deal with a signed divide and an unsigned compare (and
6500 // vice versa). This is because (x /s C1) <s C2 produces different
6501 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6502 // (x /u C1) <u C2. Simply casting the operands and result won't
6503 // work. :( The if statement below tests that condition and bails
6504 // if it finds it.
6505 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6506 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6507 return 0;
6508 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006509 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006510 if (DivIsSigned && DivRHS->isAllOnesValue())
6511 return 0; // The overflow computation also screws up here
6512 if (DivRHS->isOne())
6513 return 0; // Not worth bothering, and eliminates some funny cases
6514 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006515
6516 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6517 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6518 // C2 (CI). By solving for X we can turn this into a range check
6519 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006520 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006521
6522 // Determine if the product overflows by seeing if the product is
6523 // not equal to the divide. Make sure we do the same kind of divide
6524 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006525 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6526 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006527
6528 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006529 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006530
Chris Lattner1dbfd482007-06-21 18:11:19 +00006531 // Figure out the interval that is being checked. For example, a comparison
6532 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6533 // Compute this interval based on the constants involved and the signedness of
6534 // the compare/divide. This computes a half-open interval, keeping track of
6535 // whether either value in the interval overflows. After analysis each
6536 // overflow variable is set to 0 if it's corresponding bound variable is valid
6537 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6538 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006539 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006540
Chris Lattner562ef782007-06-20 23:46:26 +00006541 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006542 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006543 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006544 HiOverflow = LoOverflow = ProdOV;
6545 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006546 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006547 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006548 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006549 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006550 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006551 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006552 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006553 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6554 HiOverflow = LoOverflow = ProdOV;
6555 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006556 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006557 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006558 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006559 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006560 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6561 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006562 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006563 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006564 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006565 true) ? -1 : 0;
6566 }
Chris Lattner562ef782007-06-20 23:46:26 +00006567 }
Dan Gohman76491272008-02-13 22:09:18 +00006568 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006569 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006570 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006571 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006572 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6574 HiOverflow = 1; // [INTMIN+1, overflow)
6575 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6576 }
Dan Gohman76491272008-02-13 22:09:18 +00006577 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006578 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006579 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006580 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006581 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006582 LoOverflow = AddWithOverflow(LoBound, HiBound,
6583 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006584 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006585 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6586 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006587 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006588 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006589 }
6590
Chris Lattner1dbfd482007-06-21 18:11:19 +00006591 // Dividing by a negative swaps the condition. LT <-> GT
6592 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006593 }
6594
6595 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006597 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006598 case ICmpInst::ICMP_EQ:
6599 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006600 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006601 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006602 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006603 ICmpInst::ICMP_UGE, X, LoBound);
6604 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006605 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006606 ICmpInst::ICMP_ULT, X, HiBound);
6607 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006608 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006609 case ICmpInst::ICMP_NE:
6610 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006611 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006612 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006613 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006614 ICmpInst::ICMP_ULT, X, LoBound);
6615 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006616 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006617 ICmpInst::ICMP_UGE, X, HiBound);
6618 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006619 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006620 case ICmpInst::ICMP_ULT:
6621 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006622 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006623 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006624 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006625 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006626 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006627 case ICmpInst::ICMP_UGT:
6628 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006629 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006630 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006631 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006632 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006633 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006634 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006635 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006636 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006637 }
6638}
6639
6640
Chris Lattner01deb9d2007-04-03 17:43:25 +00006641/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6642///
6643Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6644 Instruction *LHSI,
6645 ConstantInt *RHS) {
6646 const APInt &RHSV = RHS->getValue();
6647
6648 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006649 case Instruction::Trunc:
6650 if (ICI.isEquality() && LHSI->hasOneUse()) {
6651 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6652 // of the high bits truncated out of x are known.
6653 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6654 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6655 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6656 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6657 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6658
6659 // If all the high bits are known, we can do this xform.
6660 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6661 // Pull in the high bits from known-ones set.
6662 APInt NewRHS(RHS->getValue());
6663 NewRHS.zext(SrcBits);
6664 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006665 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006666 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006667 }
6668 }
6669 break;
6670
Duncan Sands0091bf22007-04-04 06:42:45 +00006671 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006672 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6673 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6674 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006675 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6676 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006677 Value *CompareVal = LHSI->getOperand(0);
6678
6679 // If the sign bit of the XorCST is not set, there is no change to
6680 // the operation, just stop using the Xor.
6681 if (!XorCST->getValue().isNegative()) {
6682 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006683 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006684 return &ICI;
6685 }
6686
6687 // Was the old condition true if the operand is positive?
6688 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6689
6690 // If so, the new one isn't.
6691 isTrueIfPositive ^= true;
6692
6693 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006694 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006695 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006696 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006697 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006698 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006699 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006700
6701 if (LHSI->hasOneUse()) {
6702 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6703 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6704 const APInt &SignBit = XorCST->getValue();
6705 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6706 ? ICI.getUnsignedPredicate()
6707 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006708 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006709 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006710 }
6711
6712 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006713 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006714 const APInt &NotSignBit = XorCST->getValue();
6715 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6716 ? ICI.getUnsignedPredicate()
6717 : ICI.getSignedPredicate();
6718 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006719 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006720 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006721 }
6722 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006723 }
6724 break;
6725 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6726 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6727 LHSI->getOperand(0)->hasOneUse()) {
6728 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6729
6730 // If the LHS is an AND of a truncating cast, we can widen the
6731 // and/compare to be the input width without changing the value
6732 // produced, eliminating a cast.
6733 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6734 // We can do this transformation if either the AND constant does not
6735 // have its sign bit set or if it is an equality comparison.
6736 // Extending a relational comparison when we're checking the sign
6737 // bit would not work.
6738 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006739 (ICI.isEquality() ||
6740 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006741 uint32_t BitWidth =
6742 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6743 APInt NewCST = AndCST->getValue();
6744 NewCST.zext(BitWidth);
6745 APInt NewCI = RHSV;
6746 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006747 Value *NewAnd =
6748 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006749 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006750 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006751 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006752 }
6753 }
6754
6755 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6756 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6757 // happens a LOT in code produced by the C front-end, for bitfield
6758 // access.
6759 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6760 if (Shift && !Shift->isShift())
6761 Shift = 0;
6762
6763 ConstantInt *ShAmt;
6764 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6765 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6766 const Type *AndTy = AndCST->getType(); // Type of the and.
6767
6768 // We can fold this as long as we can't shift unknown bits
6769 // into the mask. This can only happen with signed shift
6770 // rights, as they sign-extend.
6771 if (ShAmt) {
6772 bool CanFold = Shift->isLogicalShift();
6773 if (!CanFold) {
6774 // To test for the bad case of the signed shr, see if any
6775 // of the bits shifted in could be tested after the mask.
6776 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6777 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6778
6779 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6780 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6781 AndCST->getValue()) == 0)
6782 CanFold = true;
6783 }
6784
6785 if (CanFold) {
6786 Constant *NewCst;
6787 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006788 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006789 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006790 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006791
6792 // Check to see if we are shifting out any of the bits being
6793 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006794 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006795 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 // If we shifted bits out, the fold is not going to work out.
6797 // As a special case, check to see if this means that the
6798 // result is always true or false now.
6799 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006800 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006802 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006803 } else {
6804 ICI.setOperand(1, NewCst);
6805 Constant *NewAndCST;
6806 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006807 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006808 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006809 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006810 LHSI->setOperand(1, NewAndCST);
6811 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006812 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006813 return &ICI;
6814 }
6815 }
6816 }
6817
6818 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6819 // preferable because it allows the C<<Y expression to be hoisted out
6820 // of a loop if Y is invariant and X is not.
6821 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006822 ICI.isEquality() && !Shift->isArithmeticShift() &&
6823 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006824 // Compute C << Y.
6825 Value *NS;
6826 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006827 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006828 } else {
6829 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006830 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006831 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006832
6833 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006834 Value *NewAnd =
6835 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006836
6837 ICI.setOperand(0, NewAnd);
6838 return &ICI;
6839 }
6840 }
6841 break;
6842
Chris Lattnera0141b92007-07-15 20:42:37 +00006843 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6844 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6845 if (!ShAmt) break;
6846
6847 uint32_t TypeBits = RHSV.getBitWidth();
6848
6849 // Check that the shift amount is in range. If not, don't perform
6850 // undefined shifts. When the shift is visited it will be
6851 // simplified.
6852 if (ShAmt->uge(TypeBits))
6853 break;
6854
6855 if (ICI.isEquality()) {
6856 // If we are comparing against bits always shifted out, the
6857 // comparison cannot succeed.
6858 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006859 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006860 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006861 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6862 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006863 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006864 return ReplaceInstUsesWith(ICI, Cst);
6865 }
6866
6867 if (LHSI->hasOneUse()) {
6868 // Otherwise strength reduce the shift into an and.
6869 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6870 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006871 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006872 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006873
Chris Lattner74381062009-08-30 07:44:24 +00006874 Value *And =
6875 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006876 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006877 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006878 }
6879 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006880
6881 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6882 bool TrueIfSigned = false;
6883 if (LHSI->hasOneUse() &&
6884 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6885 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006886 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006887 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006888 Value *And =
6889 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006890 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006891 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006892 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006893 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006894 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006895
6896 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006897 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006898 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006899 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006900 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006901
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006902 // Check that the shift amount is in range. If not, don't perform
6903 // undefined shifts. When the shift is visited it will be
6904 // simplified.
6905 uint32_t TypeBits = RHSV.getBitWidth();
6906 if (ShAmt->uge(TypeBits))
6907 break;
6908
6909 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006910
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006911 // If we are comparing against bits always shifted out, the
6912 // comparison cannot succeed.
6913 APInt Comp = RHSV << ShAmtVal;
6914 if (LHSI->getOpcode() == Instruction::LShr)
6915 Comp = Comp.lshr(ShAmtVal);
6916 else
6917 Comp = Comp.ashr(ShAmtVal);
6918
6919 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6920 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006921 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006922 return ReplaceInstUsesWith(ICI, Cst);
6923 }
6924
6925 // Otherwise, check to see if the bits shifted out are known to be zero.
6926 // If so, we can compare against the unshifted value:
6927 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006928 if (LHSI->hasOneUse() &&
6929 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006930 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006931 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006932 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006933 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006934
Evan Chengf30752c2008-04-23 00:38:06 +00006935 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006936 // Otherwise strength reduce the shift into an and.
6937 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006938 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006939
Chris Lattner74381062009-08-30 07:44:24 +00006940 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6941 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006942 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006943 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006944 }
6945 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006946 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006947
6948 case Instruction::SDiv:
6949 case Instruction::UDiv:
6950 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6951 // Fold this div into the comparison, producing a range check.
6952 // Determine, based on the divide type, what the range is being
6953 // checked. If there is an overflow on the low or high side, remember
6954 // it, otherwise compute the range [low, hi) bounding the new value.
6955 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006956 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6957 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6958 DivRHS))
6959 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006960 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006961
6962 case Instruction::Add:
6963 // Fold: icmp pred (add, X, C1), C2
6964
6965 if (!ICI.isEquality()) {
6966 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6967 if (!LHSC) break;
6968 const APInt &LHSV = LHSC->getValue();
6969
6970 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6971 .subtract(LHSV);
6972
6973 if (ICI.isSignedPredicate()) {
6974 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006975 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006976 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006977 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006978 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006979 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006980 }
6981 } else {
6982 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006983 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006984 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006985 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006986 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006987 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006988 }
6989 }
6990 }
6991 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006992 }
6993
6994 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6995 if (ICI.isEquality()) {
6996 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6997
6998 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6999 // the second operand is a constant, simplify a bit.
7000 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7001 switch (BO->getOpcode()) {
7002 case Instruction::SRem:
7003 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7004 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7005 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7006 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007007 Value *NewRem =
7008 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7009 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007010 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007011 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007012 }
7013 }
7014 break;
7015 case Instruction::Add:
7016 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7017 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7018 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007019 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007020 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007021 } else if (RHSV == 0) {
7022 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7023 // efficiently invertible, or if the add has just this one use.
7024 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7025
Dan Gohman186a6362009-08-12 16:04:34 +00007026 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007027 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007028 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007029 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007030 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007031 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007032 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007033 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007034 }
7035 }
7036 break;
7037 case Instruction::Xor:
7038 // For the xor case, we can xor two constants together, eliminating
7039 // the explicit xor.
7040 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007041 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007042 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007043
7044 // FALLTHROUGH
7045 case Instruction::Sub:
7046 // Replace (([sub|xor] A, B) != 0) with (A != B)
7047 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007048 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007049 BO->getOperand(1));
7050 break;
7051
7052 case Instruction::Or:
7053 // If bits are being or'd in that are not present in the constant we
7054 // are comparing against, then the comparison could never succeed!
7055 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007056 Constant *NotCI = ConstantExpr::getNot(RHS);
7057 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007058 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007059 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007060 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007061 }
7062 break;
7063
7064 case Instruction::And:
7065 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7066 // If bits are being compared against that are and'd out, then the
7067 // comparison can never succeed!
7068 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007069 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007070 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007071 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007072
7073 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7074 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007075 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007076 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007077 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007078
7079 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007080 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007081 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007082 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007083 ICmpInst::Predicate pred = isICMP_NE ?
7084 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007085 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007086 }
7087
7088 // ((X & ~7) == 0) --> X < 8
7089 if (RHSV == 0 && isHighOnes(BOC)) {
7090 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007091 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007092 ICmpInst::Predicate pred = isICMP_NE ?
7093 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007094 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007095 }
7096 }
7097 default: break;
7098 }
7099 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7100 // Handle icmp {eq|ne} <intrinsic>, intcst.
7101 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007102 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007103 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007104 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007105 return &ICI;
7106 }
7107 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007108 }
7109 return 0;
7110}
7111
7112/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7113/// We only handle extending casts so far.
7114///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007115Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7116 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007117 Value *LHSCIOp = LHSCI->getOperand(0);
7118 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007119 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007120 Value *RHSCIOp;
7121
Chris Lattner8c756c12007-05-05 22:41:33 +00007122 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7123 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007124 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7125 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007126 cast<IntegerType>(DestTy)->getBitWidth()) {
7127 Value *RHSOp = 0;
7128 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007129 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007130 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7131 RHSOp = RHSC->getOperand(0);
7132 // If the pointer types don't match, insert a bitcast.
7133 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007134 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007135 }
7136
7137 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007138 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007139 }
7140
7141 // The code below only handles extension cast instructions, so far.
7142 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007143 if (LHSCI->getOpcode() != Instruction::ZExt &&
7144 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007145 return 0;
7146
Reid Spencere4d87aa2006-12-23 06:05:41 +00007147 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7148 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007149
Reid Spencere4d87aa2006-12-23 06:05:41 +00007150 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007151 // Not an extension from the same type?
7152 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007153 if (RHSCIOp->getType() != LHSCIOp->getType())
7154 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007155
Nick Lewycky4189a532008-01-28 03:48:02 +00007156 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007157 // and the other is a zext), then we can't handle this.
7158 if (CI->getOpcode() != LHSCI->getOpcode())
7159 return 0;
7160
Nick Lewycky4189a532008-01-28 03:48:02 +00007161 // Deal with equality cases early.
7162 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007163 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007164
7165 // A signed comparison of sign extended values simplifies into a
7166 // signed comparison.
7167 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007168 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007169
7170 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007171 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007172 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007173
Reid Spencere4d87aa2006-12-23 06:05:41 +00007174 // If we aren't dealing with a constant on the RHS, exit early
7175 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7176 if (!CI)
7177 return 0;
7178
7179 // Compute the constant that would happen if we truncated to SrcTy then
7180 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007181 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7182 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007183 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007184
7185 // If the re-extended constant didn't change...
7186 if (Res2 == CI) {
7187 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7188 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007189 // %A = sext i16 %X to i32
7190 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007191 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007192 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007193 // because %A may have negative value.
7194 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007195 // However, we allow this when the compare is EQ/NE, because they are
7196 // signless.
7197 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007198 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007199 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007200 }
7201
7202 // The re-extended constant changed so the constant cannot be represented
7203 // in the shorter type. Consequently, we cannot emit a simple comparison.
7204
7205 // First, handle some easy cases. We know the result cannot be equal at this
7206 // point so handle the ICI.isEquality() cases
7207 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007208 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007209 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007210 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007211
7212 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7213 // should have been folded away previously and not enter in here.
7214 Value *Result;
7215 if (isSignedCmp) {
7216 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007217 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007218 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007219 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007220 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007221 } else {
7222 // We're performing an unsigned comparison.
7223 if (isSignedExt) {
7224 // We're performing an unsigned comp with a sign extended value.
7225 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007226 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007227 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 } else {
7229 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007230 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 }
7232 }
7233
7234 // Finally, return the value computed.
7235 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007236 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007237 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007238
7239 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7240 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7241 "ICmp should be folded!");
7242 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007243 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007244 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007245}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007246
Reid Spencer832254e2007-02-02 02:16:23 +00007247Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7248 return commonShiftTransforms(I);
7249}
7250
7251Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7252 return commonShiftTransforms(I);
7253}
7254
7255Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007256 if (Instruction *R = commonShiftTransforms(I))
7257 return R;
7258
7259 Value *Op0 = I.getOperand(0);
7260
7261 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7262 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7263 if (CSI->isAllOnesValue())
7264 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007265
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007266 // See if we can turn a signed shr into an unsigned shr.
7267 if (MaskedValueIsZero(Op0,
7268 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7269 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7270
7271 // Arithmetic shifting an all-sign-bit value is a no-op.
7272 unsigned NumSignBits = ComputeNumSignBits(Op0);
7273 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7274 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007275
Chris Lattner348f6652007-12-06 01:59:46 +00007276 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007277}
7278
7279Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7280 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007281 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007282
7283 // shl X, 0 == X and shr X, 0 == X
7284 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007285 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7286 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007287 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007288
Reid Spencere4d87aa2006-12-23 06:05:41 +00007289 if (isa<UndefValue>(Op0)) {
7290 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007291 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007292 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007293 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007294 }
7295 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007296 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7297 return ReplaceInstUsesWith(I, Op0);
7298 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007299 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007300 }
7301
Dan Gohman9004c8a2009-05-21 02:28:33 +00007302 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007303 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007304 return &I;
7305
Chris Lattner2eefe512004-04-09 19:05:30 +00007306 // Try to fold constant and into select arguments.
7307 if (isa<Constant>(Op0))
7308 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007309 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007310 return R;
7311
Reid Spencerb83eb642006-10-20 07:07:24 +00007312 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007313 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7314 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007315 return 0;
7316}
7317
Reid Spencerb83eb642006-10-20 07:07:24 +00007318Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007319 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007320 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007321
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007322 // See if we can simplify any instructions used by the instruction whose sole
7323 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007324 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007325
Dan Gohmana119de82009-06-14 23:30:43 +00007326 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7327 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007328 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007329 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007330 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007331 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007332 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007333 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007334 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007335 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007336 }
7337
7338 // ((X*C1) << C2) == (X * (C1 << C2))
7339 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7340 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7341 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007342 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007343 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007344
7345 // Try to fold constant and into select arguments.
7346 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7347 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7348 return R;
7349 if (isa<PHINode>(Op0))
7350 if (Instruction *NV = FoldOpIntoPhi(I))
7351 return NV;
7352
Chris Lattner8999dd32007-12-22 09:07:47 +00007353 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7354 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7355 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7356 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7357 // place. Don't try to do this transformation in this case. Also, we
7358 // require that the input operand is a shift-by-constant so that we have
7359 // confidence that the shifts will get folded together. We could do this
7360 // xform in more cases, but it is unlikely to be profitable.
7361 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7362 isa<ConstantInt>(TrOp->getOperand(1))) {
7363 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007364 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007365 // (shift2 (shift1 & 0x00FF), c2)
7366 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007367
7368 // For logical shifts, the truncation has the effect of making the high
7369 // part of the register be zeros. Emulate this by inserting an AND to
7370 // clear the top bits as needed. This 'and' will usually be zapped by
7371 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007372 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7373 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007374 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7375
7376 // The mask we constructed says what the trunc would do if occurring
7377 // between the shifts. We want to know the effect *after* the second
7378 // shift. We know that it is a logical shift by a constant, so adjust the
7379 // mask as appropriate.
7380 if (I.getOpcode() == Instruction::Shl)
7381 MaskV <<= Op1->getZExtValue();
7382 else {
7383 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7384 MaskV = MaskV.lshr(Op1->getZExtValue());
7385 }
7386
Chris Lattner74381062009-08-30 07:44:24 +00007387 // shift1 & 0x00FF
7388 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7389 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007390
7391 // Return the value truncated to the interesting size.
7392 return new TruncInst(And, I.getType());
7393 }
7394 }
7395
Chris Lattner4d5542c2006-01-06 07:12:35 +00007396 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007397 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7398 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7399 Value *V1, *V2;
7400 ConstantInt *CC;
7401 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007402 default: break;
7403 case Instruction::Add:
7404 case Instruction::And:
7405 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007406 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007407 // These operators commute.
7408 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007409 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007410 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007411 m_Specific(Op1)))) {
7412 Value *YS = // (Y << C)
7413 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7414 // (X + (Y << C))
7415 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7416 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007417 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007418 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007419 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007420 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007421
Chris Lattner150f12a2005-09-18 06:30:59 +00007422 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007423 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007424 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007425 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007426 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007427 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007428 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007429 Value *YS = // (Y << C)
7430 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7431 Op0BO->getName());
7432 // X & (CC << C)
7433 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7434 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007435 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007436 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007437 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007438
Reid Spencera07cb7d2007-02-02 14:41:37 +00007439 // FALL THROUGH.
7440 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007441 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007442 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007443 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007444 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007445 Value *YS = // (Y << C)
7446 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7447 // (X + (Y << C))
7448 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7449 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007450 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007451 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007452 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007453 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007454
Chris Lattner13d4ab42006-05-31 21:14:00 +00007455 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007456 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7457 match(Op0BO->getOperand(0),
7458 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007459 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007460 cast<BinaryOperator>(Op0BO->getOperand(0))
7461 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007462 Value *YS = // (Y << C)
7463 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7464 // X & (CC << C)
7465 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7466 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007467
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007468 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007469 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007470
Chris Lattner11021cb2005-09-18 05:12:10 +00007471 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007472 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 }
7474
7475
7476 // If the operand is an bitwise operator with a constant RHS, and the
7477 // shift is the only use, we can pull it out of the shift.
7478 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7479 bool isValid = true; // Valid only for And, Or, Xor
7480 bool highBitSet = false; // Transform if high bit of constant set?
7481
7482 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007483 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007484 case Instruction::Add:
7485 isValid = isLeftShift;
7486 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007487 case Instruction::Or:
7488 case Instruction::Xor:
7489 highBitSet = false;
7490 break;
7491 case Instruction::And:
7492 highBitSet = true;
7493 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007494 }
7495
7496 // If this is a signed shift right, and the high bit is modified
7497 // by the logical operation, do not perform the transformation.
7498 // The highBitSet boolean indicates the value of the high bit of
7499 // the constant which would cause it to be modified for this
7500 // operation.
7501 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007502 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007503 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007504
7505 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007506 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007507
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007508 Value *NewShift =
7509 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007510 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007511
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007512 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007513 NewRHS);
7514 }
7515 }
7516 }
7517 }
7518
Chris Lattnerad0124c2006-01-06 07:52:12 +00007519 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007520 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7521 if (ShiftOp && !ShiftOp->isShift())
7522 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007523
Reid Spencerb83eb642006-10-20 07:07:24 +00007524 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007525 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007526 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7527 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007528 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7529 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7530 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007531
Zhou Sheng4351c642007-04-02 08:20:41 +00007532 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007533
7534 const IntegerType *Ty = cast<IntegerType>(I.getType());
7535
7536 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007537 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007538 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7539 // saturates.
7540 if (AmtSum >= TypeBits) {
7541 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007542 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007543 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7544 }
7545
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007546 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007547 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007548 }
7549
7550 if (ShiftOp->getOpcode() == Instruction::LShr &&
7551 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007552 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007553 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007554
Chris Lattnerb87056f2007-02-05 00:57:54 +00007555 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007556 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007557 }
7558
7559 if (ShiftOp->getOpcode() == Instruction::AShr &&
7560 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007561 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007562 if (AmtSum >= TypeBits)
7563 AmtSum = TypeBits-1;
7564
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007565 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007566
Zhou Shenge9e03f62007-03-28 15:02:20 +00007567 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007568 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007569 }
7570
Chris Lattnerb87056f2007-02-05 00:57:54 +00007571 // Okay, if we get here, one shift must be left, and the other shift must be
7572 // right. See if the amounts are equal.
7573 if (ShiftAmt1 == ShiftAmt2) {
7574 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7575 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007576 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007577 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007578 }
7579 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7580 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007581 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007582 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007583 }
7584 // We can simplify ((X << C) >>s C) into a trunc + sext.
7585 // NOTE: we could do this for any C, but that would make 'unusual' integer
7586 // types. For now, just stick to ones well-supported by the code
7587 // generators.
7588 const Type *SExtType = 0;
7589 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007590 case 1 :
7591 case 8 :
7592 case 16 :
7593 case 32 :
7594 case 64 :
7595 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007596 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007597 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007598 default: break;
7599 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007600 if (SExtType)
7601 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007602 // Otherwise, we can't handle it yet.
7603 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007604 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007605
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007606 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007607 if (I.getOpcode() == Instruction::Shl) {
7608 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7609 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007610 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007611
Reid Spencer55702aa2007-03-25 21:11:44 +00007612 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007613 return BinaryOperator::CreateAnd(Shift,
7614 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007615 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007616
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007617 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 if (I.getOpcode() == Instruction::LShr) {
7619 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007620 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007621
Reid Spencerd5e30f02007-03-26 17:18:58 +00007622 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007623 return BinaryOperator::CreateAnd(Shift,
7624 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007625 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007626
7627 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7628 } else {
7629 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007630 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007631
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007632 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007633 if (I.getOpcode() == Instruction::Shl) {
7634 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7635 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007636 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7637 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007638
Reid Spencer55702aa2007-03-25 21:11:44 +00007639 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007640 return BinaryOperator::CreateAnd(Shift,
7641 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007642 }
7643
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007644 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007645 if (I.getOpcode() == Instruction::LShr) {
7646 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007647 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007648
Reid Spencer68d27cf2007-03-26 23:45:51 +00007649 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007650 return BinaryOperator::CreateAnd(Shift,
7651 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007652 }
7653
7654 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007655 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007656 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007657 return 0;
7658}
7659
Chris Lattnera1be5662002-05-02 17:06:02 +00007660
Chris Lattnercfd65102005-10-29 04:36:15 +00007661/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7662/// expression. If so, decompose it, returning some value X, such that Val is
7663/// X*Scale+Offset.
7664///
7665static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007666 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007667 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7668 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007669 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007670 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007671 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007672 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007673 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7674 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7675 if (I->getOpcode() == Instruction::Shl) {
7676 // This is a value scaled by '1 << the shift amt'.
7677 Scale = 1U << RHS->getZExtValue();
7678 Offset = 0;
7679 return I->getOperand(0);
7680 } else if (I->getOpcode() == Instruction::Mul) {
7681 // This value is scaled by 'RHS'.
7682 Scale = RHS->getZExtValue();
7683 Offset = 0;
7684 return I->getOperand(0);
7685 } else if (I->getOpcode() == Instruction::Add) {
7686 // We have X+C. Check to see if we really have (X*C2)+C1,
7687 // where C1 is divisible by C2.
7688 unsigned SubScale;
7689 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007690 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7691 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007692 Offset += RHS->getZExtValue();
7693 Scale = SubScale;
7694 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007695 }
7696 }
7697 }
7698
7699 // Otherwise, we can't look past this.
7700 Scale = 1;
7701 Offset = 0;
7702 return Val;
7703}
7704
7705
Chris Lattnerb3f83972005-10-24 06:03:58 +00007706/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7707/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007708Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007709 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007710 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007711
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007712 BuilderTy AllocaBuilder(*Builder);
7713 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7714
Chris Lattnerb53c2382005-10-24 06:22:12 +00007715 // Remove any uses of AI that are dead.
7716 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007717
Chris Lattnerb53c2382005-10-24 06:22:12 +00007718 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7719 Instruction *User = cast<Instruction>(*UI++);
7720 if (isInstructionTriviallyDead(User)) {
7721 while (UI != E && *UI == User)
7722 ++UI; // If this instruction uses AI more than once, don't break UI.
7723
Chris Lattnerb53c2382005-10-24 06:22:12 +00007724 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007725 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007726 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007727 }
7728 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007729
7730 // This requires TargetData to get the alloca alignment and size information.
7731 if (!TD) return 0;
7732
Chris Lattnerb3f83972005-10-24 06:03:58 +00007733 // Get the type really allocated and the type casted to.
7734 const Type *AllocElTy = AI.getAllocatedType();
7735 const Type *CastElTy = PTy->getElementType();
7736 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007737
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007738 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7739 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007740 if (CastElTyAlign < AllocElTyAlign) return 0;
7741
Chris Lattner39387a52005-10-24 06:35:18 +00007742 // If the allocation has multiple uses, only promote it if we are strictly
7743 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007744 // same, we open the door to infinite loops of various kinds. (A reference
7745 // from a dbg.declare doesn't count as a use for this purpose.)
7746 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7747 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007748
Duncan Sands777d2302009-05-09 07:06:46 +00007749 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7750 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007751 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007752
Chris Lattner455fcc82005-10-29 03:19:53 +00007753 // See if we can satisfy the modulus by pulling a scale out of the array
7754 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007755 unsigned ArraySizeScale;
7756 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007757 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007758 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7759 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007760
Chris Lattner455fcc82005-10-29 03:19:53 +00007761 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7762 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007763 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7764 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007765
Chris Lattner455fcc82005-10-29 03:19:53 +00007766 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7767 Value *Amt = 0;
7768 if (Scale == 1) {
7769 Amt = NumElements;
7770 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007771 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007772 // Insert before the alloca, not before the cast.
7773 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007774 }
7775
Jeff Cohen86796be2007-04-04 16:58:57 +00007776 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007777 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007778 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007779 }
7780
Chris Lattnerb3f83972005-10-24 06:03:58 +00007781 AllocationInst *New;
7782 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007783 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007784 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007785 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7786 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007787 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007788
Dale Johannesena0a66372009-03-05 00:39:02 +00007789 // If the allocation has one real use plus a dbg.declare, just remove the
7790 // declare.
7791 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7792 EraseInstFromFunction(*DI);
7793 }
7794 // If the allocation has multiple real uses, insert a cast and change all
7795 // things that used it to use the new cast. This will also hack on CI, but it
7796 // will die soon.
7797 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007798 // New is the allocation instruction, pointer typed. AI is the original
7799 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007800 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007801 AI.replaceAllUsesWith(NewCast);
7802 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007803 return ReplaceInstUsesWith(CI, New);
7804}
7805
Chris Lattner70074e02006-05-13 02:06:03 +00007806/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007807/// and return it as type Ty without inserting any new casts and without
7808/// changing the computed value. This is used by code that tries to decide
7809/// whether promoting or shrinking integer operations to wider or smaller types
7810/// will allow us to eliminate a truncate or extend.
7811///
7812/// This is a truncation operation if Ty is smaller than V->getType(), or an
7813/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007814///
7815/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7816/// should return true if trunc(V) can be computed by computing V in the smaller
7817/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7818/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7819/// efficiently truncated.
7820///
7821/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7822/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7823/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007824bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007825 unsigned CastOpc,
7826 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007827 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007828 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007829 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007830
7831 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007832 if (!I) return false;
7833
Dan Gohman6de29f82009-06-15 22:12:54 +00007834 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007835
Chris Lattner951626b2007-08-02 06:11:14 +00007836 // If this is an extension or truncate, we can often eliminate it.
7837 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7838 // If this is a cast from the destination type, we can trivially eliminate
7839 // it, and this will remove a cast overall.
7840 if (I->getOperand(0)->getType() == Ty) {
7841 // If the first operand is itself a cast, and is eliminable, do not count
7842 // this as an eliminable cast. We would prefer to eliminate those two
7843 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007844 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007845 ++NumCastsRemoved;
7846 return true;
7847 }
7848 }
7849
7850 // We can't extend or shrink something that has multiple uses: doing so would
7851 // require duplicating the instruction in general, which isn't profitable.
7852 if (!I->hasOneUse()) return false;
7853
Evan Chengf35fd542009-01-15 17:01:23 +00007854 unsigned Opc = I->getOpcode();
7855 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007856 case Instruction::Add:
7857 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007858 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007859 case Instruction::And:
7860 case Instruction::Or:
7861 case Instruction::Xor:
7862 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007863 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007864 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007865 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007866 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007867
Eli Friedman070a9812009-07-13 22:46:01 +00007868 case Instruction::UDiv:
7869 case Instruction::URem: {
7870 // UDiv and URem can be truncated if all the truncated bits are zero.
7871 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7872 uint32_t BitWidth = Ty->getScalarSizeInBits();
7873 if (BitWidth < OrigBitWidth) {
7874 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7875 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7876 MaskedValueIsZero(I->getOperand(1), Mask)) {
7877 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7878 NumCastsRemoved) &&
7879 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7880 NumCastsRemoved);
7881 }
7882 }
7883 break;
7884 }
Chris Lattner46b96052006-11-29 07:18:39 +00007885 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007886 // If we are truncating the result of this SHL, and if it's a shift of a
7887 // constant amount, we can always perform a SHL in a smaller type.
7888 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007889 uint32_t BitWidth = Ty->getScalarSizeInBits();
7890 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007891 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007892 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007893 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007894 }
7895 break;
7896 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007897 // If this is a truncate of a logical shr, we can truncate it to a smaller
7898 // lshr iff we know that the bits we would otherwise be shifting in are
7899 // already zeros.
7900 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007901 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7902 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007903 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007904 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007905 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7906 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007907 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007908 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007909 }
7910 }
Chris Lattner46b96052006-11-29 07:18:39 +00007911 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007912 case Instruction::ZExt:
7913 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007914 case Instruction::Trunc:
7915 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007916 // can safely replace it. Note that replacing it does not reduce the number
7917 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007918 if (Opc == CastOpc)
7919 return true;
7920
7921 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007922 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007923 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007924 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007925 case Instruction::Select: {
7926 SelectInst *SI = cast<SelectInst>(I);
7927 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007928 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007929 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007930 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007931 }
Chris Lattner8114b712008-06-18 04:00:49 +00007932 case Instruction::PHI: {
7933 // We can change a phi if we can change all operands.
7934 PHINode *PN = cast<PHINode>(I);
7935 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7936 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007937 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007938 return false;
7939 return true;
7940 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007941 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007942 // TODO: Can handle more cases here.
7943 break;
7944 }
7945
7946 return false;
7947}
7948
7949/// EvaluateInDifferentType - Given an expression that
7950/// CanEvaluateInDifferentType returns true for, actually insert the code to
7951/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007952Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007953 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007954 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007955 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007956 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007957
7958 // Otherwise, it must be an instruction.
7959 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007960 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007961 unsigned Opc = I->getOpcode();
7962 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007963 case Instruction::Add:
7964 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007965 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007966 case Instruction::And:
7967 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007968 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007969 case Instruction::AShr:
7970 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007971 case Instruction::Shl:
7972 case Instruction::UDiv:
7973 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007974 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007975 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007976 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007977 break;
7978 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007979 case Instruction::Trunc:
7980 case Instruction::ZExt:
7981 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007982 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007983 // just return the source. There's no need to insert it because it is not
7984 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007985 if (I->getOperand(0)->getType() == Ty)
7986 return I->getOperand(0);
7987
Chris Lattner8114b712008-06-18 04:00:49 +00007988 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007989 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007990 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007991 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007992 case Instruction::Select: {
7993 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7994 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7995 Res = SelectInst::Create(I->getOperand(0), True, False);
7996 break;
7997 }
Chris Lattner8114b712008-06-18 04:00:49 +00007998 case Instruction::PHI: {
7999 PHINode *OPN = cast<PHINode>(I);
8000 PHINode *NPN = PHINode::Create(Ty);
8001 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8002 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8003 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8004 }
8005 Res = NPN;
8006 break;
8007 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008008 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008009 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008010 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008011 break;
8012 }
8013
Chris Lattner8114b712008-06-18 04:00:49 +00008014 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008015 return InsertNewInstBefore(Res, *I);
8016}
8017
Reid Spencer3da59db2006-11-27 01:05:10 +00008018/// @brief Implement the transforms common to all CastInst visitors.
8019Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008020 Value *Src = CI.getOperand(0);
8021
Dan Gohman23d9d272007-05-11 21:10:54 +00008022 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008023 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008024 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008025 if (Instruction::CastOps opc =
8026 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8027 // The first cast (CSrc) is eliminable so we need to fix up or replace
8028 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008029 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008030 }
8031 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008032
Reid Spencer3da59db2006-11-27 01:05:10 +00008033 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008034 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8035 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8036 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008037
8038 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008039 if (isa<PHINode>(Src))
8040 if (Instruction *NV = FoldOpIntoPhi(CI))
8041 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008042
Reid Spencer3da59db2006-11-27 01:05:10 +00008043 return 0;
8044}
8045
Chris Lattner46cd5a12009-01-09 05:44:56 +00008046/// FindElementAtOffset - Given a type and a constant offset, determine whether
8047/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008048/// the specified offset. If so, fill them into NewIndices and return the
8049/// resultant element type, otherwise return null.
8050static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8051 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008052 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008053 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008054 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008055 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008056
8057 // Start with the index over the outer type. Note that the type size
8058 // might be zero (even if the offset isn't zero) if the indexed type
8059 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008060 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008061 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008062 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008063 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008064 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008065
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008066 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008067 if (Offset < 0) {
8068 --FirstIdx;
8069 Offset += TySize;
8070 assert(Offset >= 0);
8071 }
8072 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8073 }
8074
Owen Andersoneed707b2009-07-24 23:12:02 +00008075 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008076
8077 // Index into the types. If we fail, set OrigBase to null.
8078 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008079 // Indexing into tail padding between struct/array elements.
8080 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008081 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008082
Chris Lattner46cd5a12009-01-09 05:44:56 +00008083 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8084 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008085 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8086 "Offset must stay within the indexed type");
8087
Chris Lattner46cd5a12009-01-09 05:44:56 +00008088 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008089 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008090
8091 Offset -= SL->getElementOffset(Elt);
8092 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008093 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008094 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008095 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008096 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008097 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008098 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008099 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008100 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008101 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008102 }
8103 }
8104
Chris Lattner3914f722009-01-24 01:00:13 +00008105 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008106}
8107
Chris Lattnerd3e28342007-04-27 17:44:50 +00008108/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8109Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8110 Value *Src = CI.getOperand(0);
8111
Chris Lattnerd3e28342007-04-27 17:44:50 +00008112 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008113 // If casting the result of a getelementptr instruction with no offset, turn
8114 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008115 if (GEP->hasAllZeroIndices()) {
8116 // Changing the cast operand is usually not a good idea but it is safe
8117 // here because the pointer operand is being replaced with another
8118 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008119 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008120 CI.setOperand(0, GEP->getOperand(0));
8121 return &CI;
8122 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008123
8124 // If the GEP has a single use, and the base pointer is a bitcast, and the
8125 // GEP computes a constant offset, see if we can convert these three
8126 // instructions into fewer. This typically happens with unions and other
8127 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008128 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008129 if (GEP->hasAllConstantIndices()) {
8130 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008131 ConstantInt *OffsetV =
8132 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008133 int64_t Offset = OffsetV->getSExtValue();
8134
8135 // Get the base pointer input of the bitcast, and the type it points to.
8136 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8137 const Type *GEPIdxTy =
8138 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008139 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008140 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008141 // If we were able to index down into an element, create the GEP
8142 // and bitcast the result. This eliminates one bitcast, potentially
8143 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008144 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8145 Builder->CreateInBoundsGEP(OrigBase,
8146 NewIndices.begin(), NewIndices.end()) :
8147 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008148 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008149
Chris Lattner46cd5a12009-01-09 05:44:56 +00008150 if (isa<BitCastInst>(CI))
8151 return new BitCastInst(NGEP, CI.getType());
8152 assert(isa<PtrToIntInst>(CI));
8153 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008154 }
8155 }
8156 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008157 }
8158
8159 return commonCastTransforms(CI);
8160}
8161
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008162/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8163/// type like i42. We don't want to introduce operations on random non-legal
8164/// integer types where they don't already exist in the code. In the future,
8165/// we should consider making this based off target-data, so that 32-bit targets
8166/// won't get i64 operations etc.
8167static bool isSafeIntegerType(const Type *Ty) {
8168 switch (Ty->getPrimitiveSizeInBits()) {
8169 case 8:
8170 case 16:
8171 case 32:
8172 case 64:
8173 return true;
8174 default:
8175 return false;
8176 }
8177}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008178
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008179/// commonIntCastTransforms - This function implements the common transforms
8180/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008181Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8182 if (Instruction *Result = commonCastTransforms(CI))
8183 return Result;
8184
8185 Value *Src = CI.getOperand(0);
8186 const Type *SrcTy = Src->getType();
8187 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008188 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8189 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008190
Reid Spencer3da59db2006-11-27 01:05:10 +00008191 // See if we can simplify any instructions used by the LHS whose sole
8192 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008193 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008194 return &CI;
8195
8196 // If the source isn't an instruction or has more than one use then we
8197 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008198 Instruction *SrcI = dyn_cast<Instruction>(Src);
8199 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008200 return 0;
8201
Chris Lattnerc739cd62007-03-03 05:27:34 +00008202 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008203 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008204 // Only do this if the dest type is a simple type, don't convert the
8205 // expression tree to something weird like i93 unless the source is also
8206 // strange.
8207 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008208 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8209 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008210 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008211 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008212 // eliminates the cast, so it is always a win. If this is a zero-extension,
8213 // we need to do an AND to maintain the clear top-part of the computation,
8214 // so we require that the input have eliminated at least one cast. If this
8215 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008216 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008217 bool DoXForm = false;
8218 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008219 switch (CI.getOpcode()) {
8220 default:
8221 // All the others use floating point so we shouldn't actually
8222 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008223 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008224 case Instruction::Trunc:
8225 DoXForm = true;
8226 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008227 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008228 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008229 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008230 // If it's unnecessary to issue an AND to clear the high bits, it's
8231 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008232 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008233 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8234 if (MaskedValueIsZero(TryRes, Mask))
8235 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008236
8237 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008238 if (TryI->use_empty())
8239 EraseInstFromFunction(*TryI);
8240 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008241 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008242 }
Evan Chengf35fd542009-01-15 17:01:23 +00008243 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008244 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008245 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008246 // If we do not have to emit the truncate + sext pair, then it's always
8247 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008248 //
8249 // It's not safe to eliminate the trunc + sext pair if one of the
8250 // eliminated cast is a truncate. e.g.
8251 // t2 = trunc i32 t1 to i16
8252 // t3 = sext i16 t2 to i32
8253 // !=
8254 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008255 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008256 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8257 if (NumSignBits > (DestBitSize - SrcBitSize))
8258 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008259
8260 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008261 if (TryI->use_empty())
8262 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008263 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008264 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008265 }
Evan Chengf35fd542009-01-15 17:01:23 +00008266 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008267
8268 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008269 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8270 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008271 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8272 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008273 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008274 // Just replace this cast with the result.
8275 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008276
Reid Spencer3da59db2006-11-27 01:05:10 +00008277 assert(Res->getType() == DestTy);
8278 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008279 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008280 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008281 // Just replace this cast with the result.
8282 return ReplaceInstUsesWith(CI, Res);
8283 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008284 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008285
8286 // If the high bits are already zero, just replace this cast with the
8287 // result.
8288 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8289 if (MaskedValueIsZero(Res, Mask))
8290 return ReplaceInstUsesWith(CI, Res);
8291
8292 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008293 Constant *C = ConstantInt::get(*Context,
8294 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008295 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008296 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008297 case Instruction::SExt: {
8298 // If the high bits are already filled with sign bit, just replace this
8299 // cast with the result.
8300 unsigned NumSignBits = ComputeNumSignBits(Res);
8301 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008302 return ReplaceInstUsesWith(CI, Res);
8303
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008305 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008306 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008307 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 }
8309 }
8310
8311 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8312 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8313
8314 switch (SrcI->getOpcode()) {
8315 case Instruction::Add:
8316 case Instruction::Mul:
8317 case Instruction::And:
8318 case Instruction::Or:
8319 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008320 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008321 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8322 // Don't insert two casts unless at least one can be eliminated.
8323 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008324 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008325 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8326 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008327 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008328 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008329 }
8330 }
8331
8332 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8333 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8334 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008335 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008336 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008337 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008338 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008339 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008340 }
8341 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008342
Eli Friedman65445c52009-07-13 21:45:57 +00008343 case Instruction::Shl: {
8344 // Canonicalize trunc inside shl, if we can.
8345 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8346 if (CI && DestBitSize < SrcBitSize &&
8347 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008348 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8349 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008350 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008351 }
8352 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008353 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008354 }
8355 return 0;
8356}
8357
Chris Lattner8a9f5712007-04-11 06:57:46 +00008358Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008359 if (Instruction *Result = commonIntCastTransforms(CI))
8360 return Result;
8361
8362 Value *Src = CI.getOperand(0);
8363 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008364 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8365 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008366
8367 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008368 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008369 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008370 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008371 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008372 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008373 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008374
Chris Lattner4f9797d2009-03-24 18:15:30 +00008375 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8376 ConstantInt *ShAmtV = 0;
8377 Value *ShiftOp = 0;
8378 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008379 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008380 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8381
8382 // Get a mask for the bits shifting in.
8383 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8384 if (MaskedValueIsZero(ShiftOp, Mask)) {
8385 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008386 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008387
8388 // Okay, we can shrink this. Truncate the input, then return a new
8389 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008390 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008391 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008392 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008393 }
8394 }
8395
8396 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008397}
8398
Evan Chengb98a10e2008-03-24 00:21:34 +00008399/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8400/// in order to eliminate the icmp.
8401Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8402 bool DoXform) {
8403 // If we are just checking for a icmp eq of a single bit and zext'ing it
8404 // to an integer, then shift the bit to the appropriate place and then
8405 // cast to integer to avoid the comparison.
8406 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8407 const APInt &Op1CV = Op1C->getValue();
8408
8409 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8410 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8411 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8412 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8413 if (!DoXform) return ICI;
8414
8415 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008416 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008417 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008418 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008419 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008420 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008421
8422 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008423 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008424 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008425 }
8426
8427 return ReplaceInstUsesWith(CI, In);
8428 }
8429
8430
8431
8432 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8433 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8434 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8435 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8436 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8437 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8438 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8439 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8440 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8441 // This only works for EQ and NE
8442 ICI->isEquality()) {
8443 // If Op1C some other power of two, convert:
8444 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8445 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8446 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8447 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8448
8449 APInt KnownZeroMask(~KnownZero);
8450 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8451 if (!DoXform) return ICI;
8452
8453 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8454 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8455 // (X&4) == 2 --> false
8456 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008457 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008458 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008459 return ReplaceInstUsesWith(CI, Res);
8460 }
8461
8462 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8463 Value *In = ICI->getOperand(0);
8464 if (ShiftAmt) {
8465 // Perform a logical shr by shiftamt.
8466 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008467 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8468 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008469 }
8470
8471 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008472 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008473 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008474 }
8475
8476 if (CI.getType() == In->getType())
8477 return ReplaceInstUsesWith(CI, In);
8478 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008479 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008480 }
8481 }
8482 }
8483
8484 return 0;
8485}
8486
Chris Lattner8a9f5712007-04-11 06:57:46 +00008487Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008488 // If one of the common conversion will work ..
8489 if (Instruction *Result = commonIntCastTransforms(CI))
8490 return Result;
8491
8492 Value *Src = CI.getOperand(0);
8493
Chris Lattnera84f47c2009-02-17 20:47:23 +00008494 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8495 // types and if the sizes are just right we can convert this into a logical
8496 // 'and' which will be much cheaper than the pair of casts.
8497 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8498 // Get the sizes of the types involved. We know that the intermediate type
8499 // will be smaller than A or C, but don't know the relation between A and C.
8500 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008501 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8502 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8503 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008504 // If we're actually extending zero bits, then if
8505 // SrcSize < DstSize: zext(a & mask)
8506 // SrcSize == DstSize: a & mask
8507 // SrcSize > DstSize: trunc(a) & mask
8508 if (SrcSize < DstSize) {
8509 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008510 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008511 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008512 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008513 }
8514
8515 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008516 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008517 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008518 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008519 }
8520 if (SrcSize > DstSize) {
8521 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008522 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008523 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008524 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008525 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008526 }
8527 }
8528
Evan Chengb98a10e2008-03-24 00:21:34 +00008529 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8530 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008531
Evan Chengb98a10e2008-03-24 00:21:34 +00008532 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8533 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8534 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8535 // of the (zext icmp) will be transformed.
8536 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8537 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8538 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8539 (transformZExtICmp(LHS, CI, false) ||
8540 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008541 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8542 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008543 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008544 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008545 }
8546
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008547 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008548 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8549 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8550 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8551 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008552 if (TI0->getType() == CI.getType())
8553 return
8554 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008555 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008556 }
8557
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008558 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8559 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8560 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8561 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8562 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8563 And->getOperand(1) == C)
8564 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8565 Value *TI0 = TI->getOperand(0);
8566 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008567 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008568 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008569 return BinaryOperator::CreateXor(NewAnd, ZC);
8570 }
8571 }
8572
Reid Spencer3da59db2006-11-27 01:05:10 +00008573 return 0;
8574}
8575
Chris Lattner8a9f5712007-04-11 06:57:46 +00008576Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008577 if (Instruction *I = commonIntCastTransforms(CI))
8578 return I;
8579
Chris Lattner8a9f5712007-04-11 06:57:46 +00008580 Value *Src = CI.getOperand(0);
8581
Dan Gohman1975d032008-10-30 20:40:10 +00008582 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008583 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008584 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008585 Constant::getAllOnesValue(CI.getType()),
8586 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008587
8588 // See if the value being truncated is already sign extended. If so, just
8589 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008590 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008591 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008592 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8593 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8594 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008595 unsigned NumSignBits = ComputeNumSignBits(Op);
8596
8597 if (OpBits == DestBits) {
8598 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8599 // bits, it is already ready.
8600 if (NumSignBits > DestBits-MidBits)
8601 return ReplaceInstUsesWith(CI, Op);
8602 } else if (OpBits < DestBits) {
8603 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8604 // bits, just sext from i32.
8605 if (NumSignBits > OpBits-MidBits)
8606 return new SExtInst(Op, CI.getType(), "tmp");
8607 } else {
8608 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8609 // bits, just truncate to i32.
8610 if (NumSignBits > OpBits-MidBits)
8611 return new TruncInst(Op, CI.getType(), "tmp");
8612 }
8613 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008614
8615 // If the input is a shl/ashr pair of a same constant, then this is a sign
8616 // extension from a smaller value. If we could trust arbitrary bitwidth
8617 // integers, we could turn this into a truncate to the smaller bit and then
8618 // use a sext for the whole extension. Since we don't, look deeper and check
8619 // for a truncate. If the source and dest are the same type, eliminate the
8620 // trunc and extend and just do shifts. For example, turn:
8621 // %a = trunc i32 %i to i8
8622 // %b = shl i8 %a, 6
8623 // %c = ashr i8 %b, 6
8624 // %d = sext i8 %c to i32
8625 // into:
8626 // %a = shl i32 %i, 30
8627 // %d = ashr i32 %a, 30
8628 Value *A = 0;
8629 ConstantInt *BA = 0, *CA = 0;
8630 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008631 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008632 BA == CA && isa<TruncInst>(A)) {
8633 Value *I = cast<TruncInst>(A)->getOperand(0);
8634 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008635 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8636 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008637 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008638 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008639 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008640 return BinaryOperator::CreateAShr(I, ShAmtV);
8641 }
8642 }
8643
Chris Lattnerba417832007-04-11 06:12:58 +00008644 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008645}
8646
Chris Lattnerb7530652008-01-27 05:29:54 +00008647/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8648/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008649static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008650 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008651 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008652 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008653 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8654 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008655 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008656 return 0;
8657}
8658
8659/// LookThroughFPExtensions - If this is an fp extension instruction, look
8660/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008661static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008662 if (Instruction *I = dyn_cast<Instruction>(V))
8663 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008664 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008665
8666 // If this value is a constant, return the constant in the smallest FP type
8667 // that can accurately represent it. This allows us to turn
8668 // (float)((double)X+2.0) into x+2.0f.
8669 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008670 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008671 return V; // No constant folding of this.
8672 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008673 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008674 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008675 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008676 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008677 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008678 return V;
8679 // Don't try to shrink to various long double types.
8680 }
8681
8682 return V;
8683}
8684
8685Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8686 if (Instruction *I = commonCastTransforms(CI))
8687 return I;
8688
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008689 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008690 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008691 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008692 // many builtins (sqrt, etc).
8693 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8694 if (OpI && OpI->hasOneUse()) {
8695 switch (OpI->getOpcode()) {
8696 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008697 case Instruction::FAdd:
8698 case Instruction::FSub:
8699 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008700 case Instruction::FDiv:
8701 case Instruction::FRem:
8702 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008703 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8704 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008705 if (LHSTrunc->getType() != SrcTy &&
8706 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008707 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008708 // If the source types were both smaller than the destination type of
8709 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008710 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8711 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008712 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8713 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008714 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008715 }
8716 }
8717 break;
8718 }
8719 }
8720 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008721}
8722
8723Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8724 return commonCastTransforms(CI);
8725}
8726
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008727Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008728 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8729 if (OpI == 0)
8730 return commonCastTransforms(FI);
8731
8732 // fptoui(uitofp(X)) --> X
8733 // fptoui(sitofp(X)) --> X
8734 // This is safe if the intermediate type has enough bits in its mantissa to
8735 // accurately represent all values of X. For example, do not do this with
8736 // i64->float->i64. This is also safe for sitofp case, because any negative
8737 // 'X' value would cause an undefined result for the fptoui.
8738 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8739 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008740 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008741 OpI->getType()->getFPMantissaWidth())
8742 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008743
8744 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008745}
8746
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008747Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008748 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8749 if (OpI == 0)
8750 return commonCastTransforms(FI);
8751
8752 // fptosi(sitofp(X)) --> X
8753 // fptosi(uitofp(X)) --> X
8754 // This is safe if the intermediate type has enough bits in its mantissa to
8755 // accurately represent all values of X. For example, do not do this with
8756 // i64->float->i64. This is also safe for sitofp case, because any negative
8757 // 'X' value would cause an undefined result for the fptoui.
8758 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8759 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008760 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008761 OpI->getType()->getFPMantissaWidth())
8762 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008763
8764 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008765}
8766
8767Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8768 return commonCastTransforms(CI);
8769}
8770
8771Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8772 return commonCastTransforms(CI);
8773}
8774
Chris Lattnera0e69692009-03-24 18:35:40 +00008775Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8776 // If the destination integer type is smaller than the intptr_t type for
8777 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8778 // trunc to be exposed to other transforms. Don't do this for extending
8779 // ptrtoint's, because we don't know if the target sign or zero extends its
8780 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008781 if (TD &&
8782 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008783 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8784 TD->getIntPtrType(CI.getContext()),
8785 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008786 return new TruncInst(P, CI.getType());
8787 }
8788
Chris Lattnerd3e28342007-04-27 17:44:50 +00008789 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008790}
8791
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008792Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008793 // If the source integer type is larger than the intptr_t type for
8794 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8795 // allows the trunc to be exposed to other transforms. Don't do this for
8796 // extending inttoptr's, because we don't know if the target sign or zero
8797 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008798 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008799 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008800 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8801 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008802 return new IntToPtrInst(P, CI.getType());
8803 }
8804
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008805 if (Instruction *I = commonCastTransforms(CI))
8806 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008807
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008808 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008809}
8810
Chris Lattnerd3e28342007-04-27 17:44:50 +00008811Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008812 // If the operands are integer typed then apply the integer transforms,
8813 // otherwise just apply the common ones.
8814 Value *Src = CI.getOperand(0);
8815 const Type *SrcTy = Src->getType();
8816 const Type *DestTy = CI.getType();
8817
Eli Friedman7e25d452009-07-13 20:53:00 +00008818 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008819 if (Instruction *I = commonPointerCastTransforms(CI))
8820 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008821 } else {
8822 if (Instruction *Result = commonCastTransforms(CI))
8823 return Result;
8824 }
8825
8826
8827 // Get rid of casts from one type to the same type. These are useless and can
8828 // be replaced by the operand.
8829 if (DestTy == Src->getType())
8830 return ReplaceInstUsesWith(CI, Src);
8831
Reid Spencer3da59db2006-11-27 01:05:10 +00008832 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008833 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8834 const Type *DstElTy = DstPTy->getElementType();
8835 const Type *SrcElTy = SrcPTy->getElementType();
8836
Nate Begeman83ad90a2008-03-31 00:22:16 +00008837 // If the address spaces don't match, don't eliminate the bitcast, which is
8838 // required for changing types.
8839 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8840 return 0;
8841
Victor Hernandez83d63912009-09-18 22:35:49 +00008842 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00008843 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00008844 // There is no need to modify malloc calls because it is their bitcast that
8845 // needs to be cleaned up.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008846 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8847 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8848 return V;
8849
Chris Lattnerd717c182007-05-05 22:32:24 +00008850 // If the source and destination are pointers, and this cast is equivalent
8851 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008852 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008853 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008854 unsigned NumZeros = 0;
8855 while (SrcElTy != DstElTy &&
8856 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8857 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8858 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8859 ++NumZeros;
8860 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008861
Chris Lattnerd3e28342007-04-27 17:44:50 +00008862 // If we found a path from the src to dest, create the getelementptr now.
8863 if (SrcElTy == DstElTy) {
8864 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008865 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8866 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00008867 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008868 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008869
Eli Friedman2451a642009-07-18 23:06:53 +00008870 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8871 if (DestVTy->getNumElements() == 1) {
8872 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008873 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008874 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008875 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008876 }
8877 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8878 }
8879 }
8880
8881 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8882 if (SrcVTy->getNumElements() == 1) {
8883 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008884 Value *Elem =
8885 Builder->CreateExtractElement(Src,
8886 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008887 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8888 }
8889 }
8890 }
8891
Reid Spencer3da59db2006-11-27 01:05:10 +00008892 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8893 if (SVI->hasOneUse()) {
8894 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8895 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008896 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008897 cast<VectorType>(DestTy)->getNumElements() ==
8898 SVI->getType()->getNumElements() &&
8899 SVI->getType()->getNumElements() ==
8900 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008901 CastInst *Tmp;
8902 // If either of the operands is a cast from CI.getType(), then
8903 // evaluating the shuffle in the casted destination's type will allow
8904 // us to eliminate at least one cast.
8905 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8906 Tmp->getOperand(0)->getType() == DestTy) ||
8907 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8908 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008909 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8910 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008911 // Return a new shuffle vector. Use the same element ID's, as we
8912 // know the vector types match #elts.
8913 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008914 }
8915 }
8916 }
8917 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008918 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008919}
8920
Chris Lattnere576b912004-04-09 23:46:01 +00008921/// GetSelectFoldableOperands - We want to turn code that looks like this:
8922/// %C = or %A, %B
8923/// %D = select %cond, %C, %A
8924/// into:
8925/// %C = select %cond, %B, 0
8926/// %D = or %A, %C
8927///
8928/// Assuming that the specified instruction is an operand to the select, return
8929/// a bitmask indicating which operands of this instruction are foldable if they
8930/// equal the other incoming value of the select.
8931///
8932static unsigned GetSelectFoldableOperands(Instruction *I) {
8933 switch (I->getOpcode()) {
8934 case Instruction::Add:
8935 case Instruction::Mul:
8936 case Instruction::And:
8937 case Instruction::Or:
8938 case Instruction::Xor:
8939 return 3; // Can fold through either operand.
8940 case Instruction::Sub: // Can only fold on the amount subtracted.
8941 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008942 case Instruction::LShr:
8943 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008944 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008945 default:
8946 return 0; // Cannot fold
8947 }
8948}
8949
8950/// GetSelectFoldableConstant - For the same transformation as the previous
8951/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008952static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008953 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008954 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008955 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008956 case Instruction::Add:
8957 case Instruction::Sub:
8958 case Instruction::Or:
8959 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008960 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008961 case Instruction::LShr:
8962 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008963 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008964 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008965 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008966 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008967 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008968 }
8969}
8970
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008971/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8972/// have the same opcode and only one use each. Try to simplify this.
8973Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8974 Instruction *FI) {
8975 if (TI->getNumOperands() == 1) {
8976 // If this is a non-volatile load or a cast from the same type,
8977 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008978 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008979 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8980 return 0;
8981 } else {
8982 return 0; // unknown unary op.
8983 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008984
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008985 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008986 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008987 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008988 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008989 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008990 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008991 }
8992
Reid Spencer832254e2007-02-02 02:16:23 +00008993 // Only handle binary operators here.
8994 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008995 return 0;
8996
8997 // Figure out if the operations have any operands in common.
8998 Value *MatchOp, *OtherOpT, *OtherOpF;
8999 bool MatchIsOpZero;
9000 if (TI->getOperand(0) == FI->getOperand(0)) {
9001 MatchOp = TI->getOperand(0);
9002 OtherOpT = TI->getOperand(1);
9003 OtherOpF = FI->getOperand(1);
9004 MatchIsOpZero = true;
9005 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9006 MatchOp = TI->getOperand(1);
9007 OtherOpT = TI->getOperand(0);
9008 OtherOpF = FI->getOperand(0);
9009 MatchIsOpZero = false;
9010 } else if (!TI->isCommutative()) {
9011 return 0;
9012 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9013 MatchOp = TI->getOperand(0);
9014 OtherOpT = TI->getOperand(1);
9015 OtherOpF = FI->getOperand(0);
9016 MatchIsOpZero = true;
9017 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9018 MatchOp = TI->getOperand(1);
9019 OtherOpT = TI->getOperand(0);
9020 OtherOpF = FI->getOperand(1);
9021 MatchIsOpZero = true;
9022 } else {
9023 return 0;
9024 }
9025
9026 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009027 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9028 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009029 InsertNewInstBefore(NewSI, SI);
9030
9031 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9032 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009033 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009034 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009035 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009036 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009037 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009038 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009039}
9040
Evan Chengde621922009-03-31 20:42:45 +00009041static bool isSelect01(Constant *C1, Constant *C2) {
9042 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9043 if (!C1I)
9044 return false;
9045 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9046 if (!C2I)
9047 return false;
9048 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9049}
9050
9051/// FoldSelectIntoOp - Try fold the select into one of the operands to
9052/// facilitate further optimization.
9053Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9054 Value *FalseVal) {
9055 // See the comment above GetSelectFoldableOperands for a description of the
9056 // transformation we are doing here.
9057 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9058 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9059 !isa<Constant>(FalseVal)) {
9060 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9061 unsigned OpToFold = 0;
9062 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9063 OpToFold = 1;
9064 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9065 OpToFold = 2;
9066 }
9067
9068 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009069 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009070 Value *OOp = TVI->getOperand(2-OpToFold);
9071 // Avoid creating select between 2 constants unless it's selecting
9072 // between 0 and 1.
9073 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9074 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9075 InsertNewInstBefore(NewSel, SI);
9076 NewSel->takeName(TVI);
9077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9078 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009079 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009080 }
9081 }
9082 }
9083 }
9084 }
9085
9086 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9087 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9088 !isa<Constant>(TrueVal)) {
9089 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9090 unsigned OpToFold = 0;
9091 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9092 OpToFold = 1;
9093 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9094 OpToFold = 2;
9095 }
9096
9097 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009098 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009099 Value *OOp = FVI->getOperand(2-OpToFold);
9100 // Avoid creating select between 2 constants unless it's selecting
9101 // between 0 and 1.
9102 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9103 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9104 InsertNewInstBefore(NewSel, SI);
9105 NewSel->takeName(FVI);
9106 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9107 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009108 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009109 }
9110 }
9111 }
9112 }
9113 }
9114
9115 return 0;
9116}
9117
Dan Gohman81b28ce2008-09-16 18:46:06 +00009118/// visitSelectInstWithICmp - Visit a SelectInst that has an
9119/// ICmpInst as its first operand.
9120///
9121Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9122 ICmpInst *ICI) {
9123 bool Changed = false;
9124 ICmpInst::Predicate Pred = ICI->getPredicate();
9125 Value *CmpLHS = ICI->getOperand(0);
9126 Value *CmpRHS = ICI->getOperand(1);
9127 Value *TrueVal = SI.getTrueValue();
9128 Value *FalseVal = SI.getFalseValue();
9129
9130 // Check cases where the comparison is with a constant that
9131 // can be adjusted to fit the min/max idiom. We may edit ICI in
9132 // place here, so make sure the select is the only user.
9133 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009134 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009135 switch (Pred) {
9136 default: break;
9137 case ICmpInst::ICMP_ULT:
9138 case ICmpInst::ICMP_SLT: {
9139 // X < MIN ? T : F --> F
9140 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9141 return ReplaceInstUsesWith(SI, FalseVal);
9142 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009143 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009144 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9145 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9146 Pred = ICmpInst::getSwappedPredicate(Pred);
9147 CmpRHS = AdjustedRHS;
9148 std::swap(FalseVal, TrueVal);
9149 ICI->setPredicate(Pred);
9150 ICI->setOperand(1, CmpRHS);
9151 SI.setOperand(1, TrueVal);
9152 SI.setOperand(2, FalseVal);
9153 Changed = true;
9154 }
9155 break;
9156 }
9157 case ICmpInst::ICMP_UGT:
9158 case ICmpInst::ICMP_SGT: {
9159 // X > MAX ? T : F --> F
9160 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9161 return ReplaceInstUsesWith(SI, FalseVal);
9162 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009163 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009164 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9165 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9166 Pred = ICmpInst::getSwappedPredicate(Pred);
9167 CmpRHS = AdjustedRHS;
9168 std::swap(FalseVal, TrueVal);
9169 ICI->setPredicate(Pred);
9170 ICI->setOperand(1, CmpRHS);
9171 SI.setOperand(1, TrueVal);
9172 SI.setOperand(2, FalseVal);
9173 Changed = true;
9174 }
9175 break;
9176 }
9177 }
9178
Dan Gohman1975d032008-10-30 20:40:10 +00009179 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9180 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009181 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009182 if (match(TrueVal, m_ConstantInt<-1>()) &&
9183 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009184 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009185 else if (match(TrueVal, m_ConstantInt<0>()) &&
9186 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009187 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9188
Dan Gohman1975d032008-10-30 20:40:10 +00009189 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9190 // If we are just checking for a icmp eq of a single bit and zext'ing it
9191 // to an integer, then shift the bit to the appropriate place and then
9192 // cast to integer to avoid the comparison.
9193 const APInt &Op1CV = CI->getValue();
9194
9195 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9196 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9197 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009198 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009199 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009200 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009201 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009202 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009203 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009204 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009205 if (In->getType() != SI.getType())
9206 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009207 true/*SExt*/, "tmp", ICI);
9208
9209 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009210 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009211 In->getName()+".not"), *ICI);
9212
9213 return ReplaceInstUsesWith(SI, In);
9214 }
9215 }
9216 }
9217
Dan Gohman81b28ce2008-09-16 18:46:06 +00009218 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9219 // Transform (X == Y) ? X : Y -> Y
9220 if (Pred == ICmpInst::ICMP_EQ)
9221 return ReplaceInstUsesWith(SI, FalseVal);
9222 // Transform (X != Y) ? X : Y -> X
9223 if (Pred == ICmpInst::ICMP_NE)
9224 return ReplaceInstUsesWith(SI, TrueVal);
9225 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9226
9227 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9228 // Transform (X == Y) ? Y : X -> X
9229 if (Pred == ICmpInst::ICMP_EQ)
9230 return ReplaceInstUsesWith(SI, FalseVal);
9231 // Transform (X != Y) ? Y : X -> Y
9232 if (Pred == ICmpInst::ICMP_NE)
9233 return ReplaceInstUsesWith(SI, TrueVal);
9234 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9235 }
9236
9237 /// NOTE: if we wanted to, this is where to detect integer ABS
9238
9239 return Changed ? &SI : 0;
9240}
9241
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009242/// isDefinedInBB - Return true if the value is an instruction defined in the
9243/// specified basicblock.
9244static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9245 const Instruction *I = dyn_cast<Instruction>(V);
9246 return I != 0 && I->getParent() == BB;
9247}
9248
9249
Chris Lattner3d69f462004-03-12 05:52:32 +00009250Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009251 Value *CondVal = SI.getCondition();
9252 Value *TrueVal = SI.getTrueValue();
9253 Value *FalseVal = SI.getFalseValue();
9254
9255 // select true, X, Y -> X
9256 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009257 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009258 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009259
9260 // select C, X, X -> X
9261 if (TrueVal == FalseVal)
9262 return ReplaceInstUsesWith(SI, TrueVal);
9263
Chris Lattnere87597f2004-10-16 18:11:37 +00009264 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9265 return ReplaceInstUsesWith(SI, FalseVal);
9266 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9267 return ReplaceInstUsesWith(SI, TrueVal);
9268 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9269 if (isa<Constant>(TrueVal))
9270 return ReplaceInstUsesWith(SI, TrueVal);
9271 else
9272 return ReplaceInstUsesWith(SI, FalseVal);
9273 }
9274
Owen Anderson1d0be152009-08-13 21:58:54 +00009275 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009276 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009277 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009278 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009279 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009280 } else {
9281 // Change: A = select B, false, C --> A = and !B, C
9282 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009283 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009284 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009285 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009286 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009287 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009288 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009289 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009290 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009291 } else {
9292 // Change: A = select B, C, true --> A = or !B, C
9293 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009294 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009295 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009296 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009297 }
9298 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009299
9300 // select a, b, a -> a&b
9301 // select a, a, b -> a|b
9302 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009303 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009304 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009305 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009306 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009307
Chris Lattner2eefe512004-04-09 19:05:30 +00009308 // Selecting between two integer constants?
9309 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9310 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009311 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009312 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009313 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009314 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009315 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009316 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009317 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009318 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009319 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009320 }
Chris Lattner457dd822004-06-09 07:59:58 +00009321
Reid Spencere4d87aa2006-12-23 06:05:41 +00009322 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009323 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009324 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009325 // non-constant value, eliminate this whole mess. This corresponds to
9326 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009327 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009328 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009329 cast<Constant>(IC->getOperand(1))->isNullValue())
9330 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9331 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009332 isa<ConstantInt>(ICA->getOperand(1)) &&
9333 (ICA->getOperand(1) == TrueValC ||
9334 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009335 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9336 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009337 // know whether we have a icmp_ne or icmp_eq and whether the
9338 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009339 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009340 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009341 Value *V = ICA;
9342 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009343 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009344 Instruction::Xor, V, ICA->getOperand(1)), SI);
9345 return ReplaceInstUsesWith(SI, V);
9346 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009347 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009348 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009349
9350 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009351 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9352 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009353 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009354 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9355 // This is not safe in general for floating point:
9356 // consider X== -0, Y== +0.
9357 // It becomes safe if either operand is a nonzero constant.
9358 ConstantFP *CFPt, *CFPf;
9359 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9360 !CFPt->getValueAPF().isZero()) ||
9361 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9362 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009363 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009364 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009365 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009366 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009367 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009368 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009369
Reid Spencere4d87aa2006-12-23 06:05:41 +00009370 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009371 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009372 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9373 // This is not safe in general for floating point:
9374 // consider X== -0, Y== +0.
9375 // It becomes safe if either operand is a nonzero constant.
9376 ConstantFP *CFPt, *CFPf;
9377 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9378 !CFPt->getValueAPF().isZero()) ||
9379 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9380 !CFPf->getValueAPF().isZero()))
9381 return ReplaceInstUsesWith(SI, FalseVal);
9382 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009383 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009384 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9385 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009386 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009387 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009388 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009389 }
9390
9391 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009392 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9393 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9394 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009395
Chris Lattner87875da2005-01-13 22:52:24 +00009396 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9397 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9398 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009399 Instruction *AddOp = 0, *SubOp = 0;
9400
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009401 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9402 if (TI->getOpcode() == FI->getOpcode())
9403 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9404 return IV;
9405
9406 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9407 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009408 if ((TI->getOpcode() == Instruction::Sub &&
9409 FI->getOpcode() == Instruction::Add) ||
9410 (TI->getOpcode() == Instruction::FSub &&
9411 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009412 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009413 } else if ((FI->getOpcode() == Instruction::Sub &&
9414 TI->getOpcode() == Instruction::Add) ||
9415 (FI->getOpcode() == Instruction::FSub &&
9416 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009417 AddOp = TI; SubOp = FI;
9418 }
9419
9420 if (AddOp) {
9421 Value *OtherAddOp = 0;
9422 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9423 OtherAddOp = AddOp->getOperand(1);
9424 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9425 OtherAddOp = AddOp->getOperand(0);
9426 }
9427
9428 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009429 // So at this point we know we have (Y -> OtherAddOp):
9430 // select C, (add X, Y), (sub X, Z)
9431 Value *NegVal; // Compute -Z
9432 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009433 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009434 } else {
9435 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009436 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009437 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009438 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009439
9440 Value *NewTrueOp = OtherAddOp;
9441 Value *NewFalseOp = NegVal;
9442 if (AddOp != TI)
9443 std::swap(NewTrueOp, NewFalseOp);
9444 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009445 SelectInst::Create(CondVal, NewTrueOp,
9446 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009447
9448 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009449 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009450 }
9451 }
9452 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009453
Chris Lattnere576b912004-04-09 23:46:01 +00009454 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009455 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009456 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9457 if (FoldI)
9458 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009459 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009460
Chris Lattner5d1704d2009-09-27 19:57:57 +00009461 // See if we can fold the select into a phi node. The true/false values have
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009462 // to be live in the predecessor blocks. If they are instructions in SI's
9463 // block, we can't map to the predecessor.
Chris Lattner5d1704d2009-09-27 19:57:57 +00009464 if (isa<PHINode>(SI.getCondition()) &&
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009465 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9466 isa<PHINode>(SI.getTrueValue())) &&
9467 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9468 isa<PHINode>(SI.getFalseValue())))
Chris Lattner5d1704d2009-09-27 19:57:57 +00009469 if (Instruction *NV = FoldOpIntoPhi(SI))
9470 return NV;
9471
Chris Lattnera1df33c2005-04-24 07:30:14 +00009472 if (BinaryOperator::isNot(CondVal)) {
9473 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9474 SI.setOperand(1, FalseVal);
9475 SI.setOperand(2, TrueVal);
9476 return &SI;
9477 }
9478
Chris Lattner3d69f462004-03-12 05:52:32 +00009479 return 0;
9480}
9481
Dan Gohmaneee962e2008-04-10 18:43:06 +00009482/// EnforceKnownAlignment - If the specified pointer points to an object that
9483/// we control, modify the object's alignment to PrefAlign. This isn't
9484/// often possible though. If alignment is important, a more reliable approach
9485/// is to simply align all global variables and allocation instructions to
9486/// their preferred alignment from the beginning.
9487///
9488static unsigned EnforceKnownAlignment(Value *V,
9489 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009490
Dan Gohmaneee962e2008-04-10 18:43:06 +00009491 User *U = dyn_cast<User>(V);
9492 if (!U) return Align;
9493
Dan Gohmanca178902009-07-17 20:47:02 +00009494 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009495 default: break;
9496 case Instruction::BitCast:
9497 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9498 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009499 // If all indexes are zero, it is just the alignment of the base pointer.
9500 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009501 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009502 if (!isa<Constant>(*i) ||
9503 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009504 AllZeroOperands = false;
9505 break;
9506 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009507
9508 if (AllZeroOperands) {
9509 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009510 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009511 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009512 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009513 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009514 }
9515
9516 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9517 // If there is a large requested alignment and we can, bump up the alignment
9518 // of the global.
9519 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009520 if (GV->getAlignment() >= PrefAlign)
9521 Align = GV->getAlignment();
9522 else {
9523 GV->setAlignment(PrefAlign);
9524 Align = PrefAlign;
9525 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009526 }
Chris Lattner42ebefa2009-09-27 21:42:46 +00009527 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9528 // If there is a requested alignment and if this is an alloca, round up.
9529 if (AI->getAlignment() >= PrefAlign)
9530 Align = AI->getAlignment();
9531 else {
9532 AI->setAlignment(PrefAlign);
9533 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +00009534 }
9535 }
9536
9537 return Align;
9538}
9539
9540/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9541/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9542/// and it is more than the alignment of the ultimate object, see if we can
9543/// increase the alignment of the ultimate object, making this check succeed.
9544unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9545 unsigned PrefAlign) {
9546 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9547 sizeof(PrefAlign) * CHAR_BIT;
9548 APInt Mask = APInt::getAllOnesValue(BitWidth);
9549 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9550 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9551 unsigned TrailZ = KnownZero.countTrailingOnes();
9552 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9553
9554 if (PrefAlign > Align)
9555 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9556
9557 // We don't need to make any adjustment.
9558 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009559}
9560
Chris Lattnerf497b022008-01-13 23:50:23 +00009561Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009562 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009563 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009564 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009565 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009566
9567 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009568 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009569 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009570 return MI;
9571 }
9572
9573 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9574 // load/store.
9575 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9576 if (MemOpLength == 0) return 0;
9577
Chris Lattner37ac6082008-01-14 00:28:35 +00009578 // Source and destination pointer types are always "i8*" for intrinsic. See
9579 // if the size is something we can handle with a single primitive load/store.
9580 // A single load+store correctly handles overlapping memory in the memmove
9581 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009582 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009583 if (Size == 0) return MI; // Delete this mem transfer.
9584
9585 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009586 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009587
Chris Lattner37ac6082008-01-14 00:28:35 +00009588 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009589 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009590 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009591
9592 // Memcpy forces the use of i8* for the source and destination. That means
9593 // that if you're using memcpy to move one double around, you'll get a cast
9594 // from double* to i8*. We'd much rather use a double load+store rather than
9595 // an i64 load+store, here because this improves the odds that the source or
9596 // dest address will be promotable. See if we can find a better type than the
9597 // integer datatype.
9598 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9599 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009600 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009601 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9602 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009603 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009604 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9605 if (STy->getNumElements() == 1)
9606 SrcETy = STy->getElementType(0);
9607 else
9608 break;
9609 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9610 if (ATy->getNumElements() == 1)
9611 SrcETy = ATy->getElementType();
9612 else
9613 break;
9614 } else
9615 break;
9616 }
9617
Dan Gohman8f8e2692008-05-23 01:52:21 +00009618 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009619 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009620 }
9621 }
9622
9623
Chris Lattnerf497b022008-01-13 23:50:23 +00009624 // If the memcpy/memmove provides better alignment info than we can
9625 // infer, use it.
9626 SrcAlign = std::max(SrcAlign, CopyAlign);
9627 DstAlign = std::max(DstAlign, CopyAlign);
9628
Chris Lattner08142f22009-08-30 19:47:22 +00009629 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9630 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009631 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9632 InsertNewInstBefore(L, *MI);
9633 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9634
9635 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009636 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009637 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009638}
Chris Lattner3d69f462004-03-12 05:52:32 +00009639
Chris Lattner69ea9d22008-04-30 06:39:11 +00009640Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9641 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009642 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009643 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009644 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009645 return MI;
9646 }
9647
9648 // Extract the length and alignment and fill if they are constant.
9649 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9650 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009651 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009652 return 0;
9653 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009654 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009655
9656 // If the length is zero, this is a no-op
9657 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9658
9659 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9660 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009661 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009662
9663 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009664 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009665
9666 // Alignment 0 is identity for alignment 1 for memset, but not store.
9667 if (Alignment == 0) Alignment = 1;
9668
9669 // Extract the fill value and store.
9670 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009671 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009672 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009673
9674 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009675 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009676 return MI;
9677 }
9678
9679 return 0;
9680}
9681
9682
Chris Lattner8b0ea312006-01-13 20:11:04 +00009683/// visitCallInst - CallInst simplification. This mostly only handles folding
9684/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9685/// the heavy lifting.
9686///
Chris Lattner9fe38862003-06-19 17:00:31 +00009687Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009688 // If the caller function is nounwind, mark the call as nounwind, even if the
9689 // callee isn't.
9690 if (CI.getParent()->getParent()->doesNotThrow() &&
9691 !CI.doesNotThrow()) {
9692 CI.setDoesNotThrow();
9693 return &CI;
9694 }
9695
Chris Lattner8b0ea312006-01-13 20:11:04 +00009696 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9697 if (!II) return visitCallSite(&CI);
9698
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009699 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9700 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009701 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009702 bool Changed = false;
9703
9704 // memmove/cpy/set of zero bytes is a noop.
9705 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9706 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9707
Chris Lattner35b9e482004-10-12 04:52:52 +00009708 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009709 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009710 // Replace the instruction with just byte operations. We would
9711 // transform other cases to loads/stores, but we don't know if
9712 // alignment is sufficient.
9713 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009714 }
9715
Chris Lattner35b9e482004-10-12 04:52:52 +00009716 // If we have a memmove and the source operation is a constant global,
9717 // then the source and dest pointers can't alias, so we can change this
9718 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009719 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009720 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9721 if (GVSrc->isConstant()) {
9722 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009723 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9724 const Type *Tys[1];
9725 Tys[0] = CI.getOperand(3)->getType();
9726 CI.setOperand(0,
9727 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009728 Changed = true;
9729 }
Chris Lattnera935db82008-05-28 05:30:41 +00009730
9731 // memmove(x,x,size) -> noop.
9732 if (MMI->getSource() == MMI->getDest())
9733 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009734 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009735
Chris Lattner95a959d2006-03-06 20:18:44 +00009736 // If we can determine a pointer alignment that is bigger than currently
9737 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009738 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009739 if (Instruction *I = SimplifyMemTransfer(MI))
9740 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009741 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9742 if (Instruction *I = SimplifyMemSet(MSI))
9743 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009744 }
9745
Chris Lattner8b0ea312006-01-13 20:11:04 +00009746 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009747 }
9748
9749 switch (II->getIntrinsicID()) {
9750 default: break;
9751 case Intrinsic::bswap:
9752 // bswap(bswap(x)) -> x
9753 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9754 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9755 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9756 break;
9757 case Intrinsic::ppc_altivec_lvx:
9758 case Intrinsic::ppc_altivec_lvxl:
9759 case Intrinsic::x86_sse_loadu_ps:
9760 case Intrinsic::x86_sse2_loadu_pd:
9761 case Intrinsic::x86_sse2_loadu_dq:
9762 // Turn PPC lvx -> load if the pointer is known aligned.
9763 // Turn X86 loadups -> load if the pointer is known aligned.
9764 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009765 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9766 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009767 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009768 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009769 break;
9770 case Intrinsic::ppc_altivec_stvx:
9771 case Intrinsic::ppc_altivec_stvxl:
9772 // Turn stvx -> store if the pointer is known aligned.
9773 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9774 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009775 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009776 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009777 return new StoreInst(II->getOperand(1), Ptr);
9778 }
9779 break;
9780 case Intrinsic::x86_sse_storeu_ps:
9781 case Intrinsic::x86_sse2_storeu_pd:
9782 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009783 // Turn X86 storeu -> store if the pointer is known aligned.
9784 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9785 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009786 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009787 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009788 return new StoreInst(II->getOperand(2), Ptr);
9789 }
9790 break;
9791
9792 case Intrinsic::x86_sse_cvttss2si: {
9793 // These intrinsics only demands the 0th element of its input vector. If
9794 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009795 unsigned VWidth =
9796 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9797 APInt DemandedElts(VWidth, 1);
9798 APInt UndefElts(VWidth, 0);
9799 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009800 UndefElts)) {
9801 II->setOperand(1, V);
9802 return II;
9803 }
9804 break;
9805 }
9806
9807 case Intrinsic::ppc_altivec_vperm:
9808 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9809 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9810 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009811
Chris Lattner0521e3c2008-06-18 04:33:20 +00009812 // Check that all of the elements are integer constants or undefs.
9813 bool AllEltsOk = true;
9814 for (unsigned i = 0; i != 16; ++i) {
9815 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9816 !isa<UndefValue>(Mask->getOperand(i))) {
9817 AllEltsOk = false;
9818 break;
9819 }
9820 }
9821
9822 if (AllEltsOk) {
9823 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009824 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9825 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009826 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009827
Chris Lattner0521e3c2008-06-18 04:33:20 +00009828 // Only extract each element once.
9829 Value *ExtractedElts[32];
9830 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9831
Chris Lattnere2ed0572006-04-06 19:19:17 +00009832 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009833 if (isa<UndefValue>(Mask->getOperand(i)))
9834 continue;
9835 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9836 Idx &= 31; // Match the hardware behavior.
9837
9838 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009839 ExtractedElts[Idx] =
9840 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9841 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9842 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009843 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009844
Chris Lattner0521e3c2008-06-18 04:33:20 +00009845 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009846 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9847 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9848 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009849 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009850 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009851 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009852 }
9853 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009854
Chris Lattner0521e3c2008-06-18 04:33:20 +00009855 case Intrinsic::stackrestore: {
9856 // If the save is right next to the restore, remove the restore. This can
9857 // happen when variable allocas are DCE'd.
9858 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9859 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9860 BasicBlock::iterator BI = SS;
9861 if (&*++BI == II)
9862 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009863 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009864 }
9865
9866 // Scan down this block to see if there is another stack restore in the
9867 // same block without an intervening call/alloca.
9868 BasicBlock::iterator BI = II;
9869 TerminatorInst *TI = II->getParent()->getTerminator();
9870 bool CannotRemove = false;
9871 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +00009872 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009873 CannotRemove = true;
9874 break;
9875 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009876 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9877 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9878 // If there is a stackrestore below this one, remove this one.
9879 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9880 return EraseInstFromFunction(CI);
9881 // Otherwise, ignore the intrinsic.
9882 } else {
9883 // If we found a non-intrinsic call, we can't remove the stack
9884 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009885 CannotRemove = true;
9886 break;
9887 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009888 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009889 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009890
9891 // If the stack restore is in a return/unwind block and if there are no
9892 // allocas or calls between the restore and the return, nuke the restore.
9893 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9894 return EraseInstFromFunction(CI);
9895 break;
9896 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009897 }
9898
Chris Lattner8b0ea312006-01-13 20:11:04 +00009899 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009900}
9901
9902// InvokeInst simplification
9903//
9904Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009905 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009906}
9907
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009908/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9909/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009910static bool isSafeToEliminateVarargsCast(const CallSite CS,
9911 const CastInst * const CI,
9912 const TargetData * const TD,
9913 const int ix) {
9914 if (!CI->isLosslessCast())
9915 return false;
9916
9917 // The size of ByVal arguments is derived from the type, so we
9918 // can't change to a type with a different size. If the size were
9919 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009920 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009921 return true;
9922
9923 const Type* SrcTy =
9924 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9925 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9926 if (!SrcTy->isSized() || !DstTy->isSized())
9927 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009928 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009929 return false;
9930 return true;
9931}
9932
Chris Lattnera44d8a22003-10-07 22:32:43 +00009933// visitCallSite - Improvements for call and invoke instructions.
9934//
9935Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009936 bool Changed = false;
9937
9938 // If the callee is a constexpr cast of a function, attempt to move the cast
9939 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009940 if (transformConstExprCastCall(CS)) return 0;
9941
Chris Lattner6c266db2003-10-07 22:54:13 +00009942 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009943
Chris Lattner08b22ec2005-05-13 07:09:09 +00009944 if (Function *CalleeF = dyn_cast<Function>(Callee))
9945 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9946 Instruction *OldCall = CS.getInstruction();
9947 // If the call and callee calling conventions don't match, this call must
9948 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009949 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009950 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009951 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009952 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009953 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009954 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9955 return EraseInstFromFunction(*OldCall);
9956 return 0;
9957 }
9958
Chris Lattner17be6352004-10-18 02:59:09 +00009959 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9960 // This instruction is not reachable, just remove it. We insert a store to
9961 // undef so that we know that this code is not reachable, despite the fact
9962 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009963 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009964 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009965 CS.getInstruction());
9966
9967 if (!CS.getInstruction()->use_empty())
9968 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009969 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009970
9971 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9972 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009973 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009974 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009975 }
Chris Lattner17be6352004-10-18 02:59:09 +00009976 return EraseInstFromFunction(*CS.getInstruction());
9977 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009978
Duncan Sandscdb6d922007-09-17 10:26:40 +00009979 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9980 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9981 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9982 return transformCallThroughTrampoline(CS);
9983
Chris Lattner6c266db2003-10-07 22:54:13 +00009984 const PointerType *PTy = cast<PointerType>(Callee->getType());
9985 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9986 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009987 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009988 // See if we can optimize any arguments passed through the varargs area of
9989 // the call.
9990 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009991 E = CS.arg_end(); I != E; ++I, ++ix) {
9992 CastInst *CI = dyn_cast<CastInst>(*I);
9993 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9994 *I = CI->getOperand(0);
9995 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009996 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009997 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009999
Duncan Sandsf0c33542007-12-19 21:13:37 +000010000 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010001 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010002 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010003 Changed = true;
10004 }
10005
Chris Lattner6c266db2003-10-07 22:54:13 +000010006 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010007}
10008
Chris Lattner9fe38862003-06-19 17:00:31 +000010009// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10010// attempt to move the cast to the arguments of the call/invoke.
10011//
10012bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10013 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10014 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010015 if (CE->getOpcode() != Instruction::BitCast ||
10016 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010017 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010018 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010019 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010020 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010021
10022 // Okay, this is a cast from a function to a different type. Unless doing so
10023 // would cause a type conversion of one of our arguments, change this call to
10024 // be a direct call with arguments casted to the appropriate types.
10025 //
10026 const FunctionType *FT = Callee->getFunctionType();
10027 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010028 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010029
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010030 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010031 return false; // TODO: Handle multiple return values.
10032
Chris Lattnerf78616b2004-01-14 06:06:08 +000010033 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010034 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010035 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010036 // Conversion is ok if changing from one pointer type to another or from
10037 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010038 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010039 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010040 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010041 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010042 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010043
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010044 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010045 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010046 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010047 return false; // Cannot transform this return value.
10048
Chris Lattner58d74912008-03-12 17:45:29 +000010049 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010050 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010051 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010052 return false; // Attribute not compatible with transformed value.
10053 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010054
Chris Lattnerf78616b2004-01-14 06:06:08 +000010055 // If the callsite is an invoke instruction, and the return value is used by
10056 // a PHI node in a successor, we cannot change the return type of the call
10057 // because there is no place to put the cast instruction (without breaking
10058 // the critical edge). Bail out in this case.
10059 if (!Caller->use_empty())
10060 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10061 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10062 UI != E; ++UI)
10063 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10064 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010065 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010066 return false;
10067 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010068
10069 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10070 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010071
Chris Lattner9fe38862003-06-19 17:00:31 +000010072 CallSite::arg_iterator AI = CS.arg_begin();
10073 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10074 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010075 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010076
10077 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010078 return false; // Cannot transform this parameter value.
10079
Devang Patel19c87462008-09-26 22:53:05 +000010080 if (CallerPAL.getParamAttributes(i + 1)
10081 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010082 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010083
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010084 // Converting from one pointer type to another or between a pointer and an
10085 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010086 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010087 (TD && ((isa<PointerType>(ParamTy) ||
10088 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10089 (isa<PointerType>(ActTy) ||
10090 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010091 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010092 }
10093
10094 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010095 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010096 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010097
Chris Lattner58d74912008-03-12 17:45:29 +000010098 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10099 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010100 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010101 // won't be dropping them. Check that these extra arguments have attributes
10102 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010103 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10104 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010105 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010106 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010107 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010108 return false;
10109 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010110
Chris Lattner9fe38862003-06-19 17:00:31 +000010111 // Okay, we decided that this is a safe thing to do: go ahead and start
10112 // inserting cast instructions as necessary...
10113 std::vector<Value*> Args;
10114 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010115 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010116 attrVec.reserve(NumCommonArgs);
10117
10118 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010119 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010120
10121 // If the return value is not being used, the type may not be compatible
10122 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010123 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010124
10125 // Add the new return attributes.
10126 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010127 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010128
10129 AI = CS.arg_begin();
10130 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10131 const Type *ParamTy = FT->getParamType(i);
10132 if ((*AI)->getType() == ParamTy) {
10133 Args.push_back(*AI);
10134 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010135 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010136 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010137 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010138 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010139
10140 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010141 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010142 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 }
10144
10145 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010146 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010147 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010148 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010149
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010150 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010151 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010152 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010153 errs() << "WARNING: While resolving call to function '"
10154 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010155 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010156 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010157 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10158 const Type *PTy = getPromotedType((*AI)->getType());
10159 if (PTy != (*AI)->getType()) {
10160 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010161 Instruction::CastOps opcode =
10162 CastInst::getCastOpcode(*AI, false, PTy, false);
10163 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010164 } else {
10165 Args.push_back(*AI);
10166 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010167
Duncan Sandse1e520f2008-01-13 08:02:44 +000010168 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010169 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010170 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010171 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010172 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010173 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010174
Devang Patel19c87462008-09-26 22:53:05 +000010175 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10176 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10177
Owen Anderson1d0be152009-08-13 21:58:54 +000010178 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010179 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010180
Eric Christophera66297a2009-07-25 02:45:27 +000010181 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10182 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010183
Chris Lattner9fe38862003-06-19 17:00:31 +000010184 Instruction *NC;
10185 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010186 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010187 Args.begin(), Args.end(),
10188 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010189 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010190 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010191 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010192 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10193 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010194 CallInst *CI = cast<CallInst>(Caller);
10195 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010196 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010197 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010198 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010199 }
10200
Chris Lattner6934a042007-02-11 01:23:03 +000010201 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010202 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010203 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010204 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010205 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010206 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010207 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010208
10209 // If this is an invoke instruction, we should insert it after the first
10210 // non-phi, instruction in the normal successor block.
10211 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010212 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010213 InsertNewInstBefore(NC, *I);
10214 } else {
10215 // Otherwise, it's a call, just insert cast right after the call instr
10216 InsertNewInstBefore(NC, *Caller);
10217 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010218 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010219 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010220 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010221 }
10222 }
10223
Chris Lattner931f8f32009-08-31 05:17:58 +000010224
10225 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010226 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000010227
10228 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010229 return true;
10230}
10231
Duncan Sandscdb6d922007-09-17 10:26:40 +000010232// transformCallThroughTrampoline - Turn a call to a function created by the
10233// init_trampoline intrinsic into a direct call to the underlying function.
10234//
10235Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10236 Value *Callee = CS.getCalledValue();
10237 const PointerType *PTy = cast<PointerType>(Callee->getType());
10238 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010239 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010240
10241 // If the call already has the 'nest' attribute somewhere then give up -
10242 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010243 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010244 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010245
10246 IntrinsicInst *Tramp =
10247 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10248
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010249 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010250 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10251 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10252
Devang Patel05988662008-09-25 21:00:45 +000010253 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010254 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010255 unsigned NestIdx = 1;
10256 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010257 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010258
10259 // Look for a parameter marked with the 'nest' attribute.
10260 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10261 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010262 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010263 // Record the parameter type and any other attributes.
10264 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010265 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010266 break;
10267 }
10268
10269 if (NestTy) {
10270 Instruction *Caller = CS.getInstruction();
10271 std::vector<Value*> NewArgs;
10272 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10273
Devang Patel05988662008-09-25 21:00:45 +000010274 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010275 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010276
Duncan Sandscdb6d922007-09-17 10:26:40 +000010277 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010278 // mean appending it. Likewise for attributes.
10279
Devang Patel19c87462008-09-26 22:53:05 +000010280 // Add any result attributes.
10281 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010282 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010283
Duncan Sandscdb6d922007-09-17 10:26:40 +000010284 {
10285 unsigned Idx = 1;
10286 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10287 do {
10288 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010289 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010290 Value *NestVal = Tramp->getOperand(3);
10291 if (NestVal->getType() != NestTy)
10292 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10293 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010294 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010295 }
10296
10297 if (I == E)
10298 break;
10299
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010300 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010301 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010302 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010303 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010304 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010305
10306 ++Idx, ++I;
10307 } while (1);
10308 }
10309
Devang Patel19c87462008-09-26 22:53:05 +000010310 // Add any function attributes.
10311 if (Attributes Attr = Attrs.getFnAttributes())
10312 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10313
Duncan Sandscdb6d922007-09-17 10:26:40 +000010314 // The trampoline may have been bitcast to a bogus type (FTy).
10315 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010316 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010317
Duncan Sandscdb6d922007-09-17 10:26:40 +000010318 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010319 NewTypes.reserve(FTy->getNumParams()+1);
10320
Duncan Sandscdb6d922007-09-17 10:26:40 +000010321 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010322 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323 {
10324 unsigned Idx = 1;
10325 FunctionType::param_iterator I = FTy->param_begin(),
10326 E = FTy->param_end();
10327
10328 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010329 if (Idx == NestIdx)
10330 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010331 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010332
10333 if (I == E)
10334 break;
10335
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010336 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010337 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338
10339 ++Idx, ++I;
10340 } while (1);
10341 }
10342
10343 // Replace the trampoline call with a direct call. Let the generic
10344 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010345 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010346 FTy->isVarArg());
10347 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010348 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010349 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010350 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010351 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10352 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010353
10354 Instruction *NewCaller;
10355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010356 NewCaller = InvokeInst::Create(NewCallee,
10357 II->getNormalDest(), II->getUnwindDest(),
10358 NewArgs.begin(), NewArgs.end(),
10359 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010360 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010361 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010362 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010363 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10364 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010365 if (cast<CallInst>(Caller)->isTailCall())
10366 cast<CallInst>(NewCaller)->setTailCall();
10367 cast<CallInst>(NewCaller)->
10368 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010369 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010370 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010371 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010372 Caller->replaceAllUsesWith(NewCaller);
10373 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010374 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010375 return 0;
10376 }
10377 }
10378
10379 // Replace the trampoline call with a direct call. Since there is no 'nest'
10380 // parameter, there is no need to adjust the argument list. Let the generic
10381 // code sort out any function type mismatches.
10382 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010383 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010384 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010385 CS.setCalledFunction(NewCallee);
10386 return CS.getInstruction();
10387}
10388
Dan Gohman9ad29202009-09-16 16:50:24 +000010389/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10390/// 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 +000010391/// and a single binop.
10392Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10393 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010394 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010395 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010396 Value *LHSVal = FirstInst->getOperand(0);
10397 Value *RHSVal = FirstInst->getOperand(1);
10398
10399 const Type *LHSType = LHSVal->getType();
10400 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010401
Dan Gohman9ad29202009-09-16 16:50:24 +000010402 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010403 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010404 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010405 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010406 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010407 // types or GEP's with different index types.
10408 I->getOperand(0)->getType() != LHSType ||
10409 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010410 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010411
10412 // If they are CmpInst instructions, check their predicates
10413 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10414 if (cast<CmpInst>(I)->getPredicate() !=
10415 cast<CmpInst>(FirstInst)->getPredicate())
10416 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010417
10418 // Keep track of which operand needs a phi node.
10419 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10420 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010421 }
Dan Gohman9ad29202009-09-16 16:50:24 +000010422
10423 // If both LHS and RHS would need a PHI, don't do this transformation,
10424 // because it would increase the number of PHIs entering the block,
10425 // which leads to higher register pressure. This is especially
10426 // bad when the PHIs are in the header of a loop.
10427 if (!LHSVal && !RHSVal)
10428 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010429
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010430 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010431
Chris Lattner7da52b22006-11-01 04:51:18 +000010432 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010433 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010434 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010435 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010436 NewLHS = PHINode::Create(LHSType,
10437 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010438 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10439 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010440 InsertNewInstBefore(NewLHS, PN);
10441 LHSVal = NewLHS;
10442 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010443
10444 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010445 NewRHS = PHINode::Create(RHSType,
10446 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010447 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10448 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010449 InsertNewInstBefore(NewRHS, PN);
10450 RHSVal = NewRHS;
10451 }
10452
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010453 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010454 if (NewLHS || NewRHS) {
10455 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10456 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10457 if (NewLHS) {
10458 Value *NewInLHS = InInst->getOperand(0);
10459 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10460 }
10461 if (NewRHS) {
10462 Value *NewInRHS = InInst->getOperand(1);
10463 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10464 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010465 }
10466 }
10467
Chris Lattner7da52b22006-11-01 04:51:18 +000010468 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010469 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010470 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010471 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010472 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010473}
10474
Chris Lattner05f18922008-12-01 02:34:36 +000010475Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10476 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10477
10478 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10479 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010480 // This is true if all GEP bases are allocas and if all indices into them are
10481 // constants.
10482 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010483
10484 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000010485 // more than one phi, which leads to higher register pressure. This is
10486 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010487 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000010488
Dan Gohman9ad29202009-09-16 16:50:24 +000010489 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000010490 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10491 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10492 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10493 GEP->getNumOperands() != FirstInst->getNumOperands())
10494 return 0;
10495
Chris Lattner36d3e322009-02-21 00:46:50 +000010496 // Keep track of whether or not all GEPs are of alloca pointers.
10497 if (AllBasePointersAreAllocas &&
10498 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10499 !GEP->hasAllConstantIndices()))
10500 AllBasePointersAreAllocas = false;
10501
Chris Lattner05f18922008-12-01 02:34:36 +000010502 // Compare the operand lists.
10503 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10504 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10505 continue;
10506
10507 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10508 // if one of the PHIs has a constant for the index. The index may be
10509 // substantially cheaper to compute for the constants, so making it a
10510 // variable index could pessimize the path. This also handles the case
10511 // for struct indices, which must always be constant.
10512 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10513 isa<ConstantInt>(GEP->getOperand(op)))
10514 return 0;
10515
10516 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10517 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000010518
10519 // If we already needed a PHI for an earlier operand, and another operand
10520 // also requires a PHI, we'd be introducing more PHIs than we're
10521 // eliminating, which increases register pressure on entry to the PHI's
10522 // block.
10523 if (NeededPhi)
10524 return 0;
10525
Chris Lattner05f18922008-12-01 02:34:36 +000010526 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000010527 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010528 }
10529 }
10530
Chris Lattner36d3e322009-02-21 00:46:50 +000010531 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010532 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010533 // offset calculation, but all the predecessors will have to materialize the
10534 // stack address into a register anyway. We'd actually rather *clone* the
10535 // load up into the predecessors so that we have a load of a gep of an alloca,
10536 // which can usually all be folded into the load.
10537 if (AllBasePointersAreAllocas)
10538 return 0;
10539
Chris Lattner05f18922008-12-01 02:34:36 +000010540 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10541 // that is variable.
10542 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10543
10544 bool HasAnyPHIs = false;
10545 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10546 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10547 Value *FirstOp = FirstInst->getOperand(i);
10548 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10549 FirstOp->getName()+".pn");
10550 InsertNewInstBefore(NewPN, PN);
10551
10552 NewPN->reserveOperandSpace(e);
10553 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10554 OperandPhis[i] = NewPN;
10555 FixedOperands[i] = NewPN;
10556 HasAnyPHIs = true;
10557 }
10558
10559
10560 // Add all operands to the new PHIs.
10561 if (HasAnyPHIs) {
10562 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10563 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10564 BasicBlock *InBB = PN.getIncomingBlock(i);
10565
10566 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10567 if (PHINode *OpPhi = OperandPhis[op])
10568 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10569 }
10570 }
10571
10572 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010573 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10574 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10575 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010576 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10577 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000010578}
10579
10580
Chris Lattner21550882009-02-23 05:56:17 +000010581/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10582/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010583/// obvious the value of the load is not changed from the point of the load to
10584/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010585///
10586/// Finally, it is safe, but not profitable, to sink a load targetting a
10587/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10588/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010589static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010590 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10591
10592 for (++BBI; BBI != E; ++BBI)
10593 if (BBI->mayWriteToMemory())
10594 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010595
10596 // Check for non-address taken alloca. If not address-taken already, it isn't
10597 // profitable to do this xform.
10598 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10599 bool isAddressTaken = false;
10600 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10601 UI != E; ++UI) {
10602 if (isa<LoadInst>(UI)) continue;
10603 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10604 // If storing TO the alloca, then the address isn't taken.
10605 if (SI->getOperand(1) == AI) continue;
10606 }
10607 isAddressTaken = true;
10608 break;
10609 }
10610
Chris Lattner36d3e322009-02-21 00:46:50 +000010611 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010612 return false;
10613 }
10614
Chris Lattner36d3e322009-02-21 00:46:50 +000010615 // If this load is a load from a GEP with a constant offset from an alloca,
10616 // then we don't want to sink it. In its present form, it will be
10617 // load [constant stack offset]. Sinking it will cause us to have to
10618 // materialize the stack addresses in each predecessor in a register only to
10619 // do a shared load from register in the successor.
10620 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10621 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10622 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10623 return false;
10624
Chris Lattner76c73142006-11-01 07:13:54 +000010625 return true;
10626}
10627
Chris Lattner9fe38862003-06-19 17:00:31 +000010628
Chris Lattnerbac32862004-11-14 19:13:23 +000010629// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10630// operator and they all are only used by the PHI, PHI together their
10631// inputs, and do the operation once, to the result of the PHI.
10632Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10633 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10634
10635 // Scan the instruction, looking for input operations that can be folded away.
10636 // If all input operands to the phi are the same instruction (e.g. a cast from
10637 // the same type or "+42") we can pull the operation through the PHI, reducing
10638 // code size and simplifying code.
10639 Constant *ConstantOp = 0;
10640 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010641 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010642 if (isa<CastInst>(FirstInst)) {
10643 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010644 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010645 // Can fold binop, compare or shift here if the RHS is a constant,
10646 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010647 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010648 if (ConstantOp == 0)
10649 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010650 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10651 isVolatile = LI->isVolatile();
10652 // We can't sink the load if the loaded value could be modified between the
10653 // load and the PHI.
10654 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010655 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010656 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010657
10658 // If the PHI is of volatile loads and the load block has multiple
10659 // successors, sinking it would remove a load of the volatile value from
10660 // the path through the other successor.
10661 if (isVolatile &&
10662 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10663 return 0;
10664
Chris Lattner9c080502006-11-01 07:43:41 +000010665 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010666 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010667 } else {
10668 return 0; // Cannot fold this operation.
10669 }
10670
10671 // Check to see if all arguments are the same operation.
10672 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10673 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10674 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010675 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010676 return 0;
10677 if (CastSrcTy) {
10678 if (I->getOperand(0)->getType() != CastSrcTy)
10679 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010680 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010681 // We can't sink the load if the loaded value could be modified between
10682 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010683 if (LI->isVolatile() != isVolatile ||
10684 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010685 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010686 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010687
Chris Lattner71042962008-07-08 17:18:32 +000010688 // If the PHI is of volatile loads and the load block has multiple
10689 // successors, sinking it would remove a load of the volatile value from
10690 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010691 if (isVolatile &&
10692 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10693 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010694
Chris Lattnerbac32862004-11-14 19:13:23 +000010695 } else if (I->getOperand(1) != ConstantOp) {
10696 return 0;
10697 }
10698 }
10699
10700 // Okay, they are all the same operation. Create a new PHI node of the
10701 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010702 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10703 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010704 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010705
10706 Value *InVal = FirstInst->getOperand(0);
10707 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010708
10709 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010710 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10711 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10712 if (NewInVal != InVal)
10713 InVal = 0;
10714 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10715 }
10716
10717 Value *PhiVal;
10718 if (InVal) {
10719 // The new PHI unions all of the same values together. This is really
10720 // common, so we handle it intelligently here for compile-time speed.
10721 PhiVal = InVal;
10722 delete NewPN;
10723 } else {
10724 InsertNewInstBefore(NewPN, PN);
10725 PhiVal = NewPN;
10726 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010727
Chris Lattnerbac32862004-11-14 19:13:23 +000010728 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010729 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010730 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010731 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010732 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010733 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010734 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010735 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010736 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10737
10738 // If this was a volatile load that we are merging, make sure to loop through
10739 // and mark all the input loads as non-volatile. If we don't do this, we will
10740 // insert a new volatile load and the old ones will not be deletable.
10741 if (isVolatile)
10742 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10743 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10744
10745 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010746}
Chris Lattnera1be5662002-05-02 17:06:02 +000010747
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010748/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10749/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010750static bool DeadPHICycle(PHINode *PN,
10751 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010752 if (PN->use_empty()) return true;
10753 if (!PN->hasOneUse()) return false;
10754
10755 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010756 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010757 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010758
10759 // Don't scan crazily complex things.
10760 if (PotentiallyDeadPHIs.size() == 16)
10761 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010762
10763 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10764 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010765
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010766 return false;
10767}
10768
Chris Lattnercf5008a2007-11-06 21:52:06 +000010769/// PHIsEqualValue - Return true if this phi node is always equal to
10770/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10771/// z = some value; x = phi (y, z); y = phi (x, z)
10772static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10773 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10774 // See if we already saw this PHI node.
10775 if (!ValueEqualPHIs.insert(PN))
10776 return true;
10777
10778 // Don't scan crazily complex things.
10779 if (ValueEqualPHIs.size() == 16)
10780 return false;
10781
10782 // Scan the operands to see if they are either phi nodes or are equal to
10783 // the value.
10784 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10785 Value *Op = PN->getIncomingValue(i);
10786 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10787 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10788 return false;
10789 } else if (Op != NonPhiInVal)
10790 return false;
10791 }
10792
10793 return true;
10794}
10795
10796
Chris Lattner473945d2002-05-06 18:06:38 +000010797// PHINode simplification
10798//
Chris Lattner7e708292002-06-25 16:13:24 +000010799Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010800 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010801 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010802
Owen Anderson7e057142006-07-10 22:03:18 +000010803 if (Value *V = PN.hasConstantValue())
10804 return ReplaceInstUsesWith(PN, V);
10805
Owen Anderson7e057142006-07-10 22:03:18 +000010806 // If all PHI operands are the same operation, pull them through the PHI,
10807 // reducing code size.
10808 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010809 isa<Instruction>(PN.getIncomingValue(1)) &&
10810 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10811 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10812 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10813 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010814 PN.getIncomingValue(0)->hasOneUse())
10815 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10816 return Result;
10817
10818 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10819 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10820 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010821 if (PN.hasOneUse()) {
10822 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10823 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010824 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010825 PotentiallyDeadPHIs.insert(&PN);
10826 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010827 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010828 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010829
10830 // If this phi has a single use, and if that use just computes a value for
10831 // the next iteration of a loop, delete the phi. This occurs with unused
10832 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10833 // common case here is good because the only other things that catch this
10834 // are induction variable analysis (sometimes) and ADCE, which is only run
10835 // late.
10836 if (PHIUser->hasOneUse() &&
10837 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10838 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010839 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010840 }
10841 }
Owen Anderson7e057142006-07-10 22:03:18 +000010842
Chris Lattnercf5008a2007-11-06 21:52:06 +000010843 // We sometimes end up with phi cycles that non-obviously end up being the
10844 // same value, for example:
10845 // z = some value; x = phi (y, z); y = phi (x, z)
10846 // where the phi nodes don't necessarily need to be in the same block. Do a
10847 // quick check to see if the PHI node only contains a single non-phi value, if
10848 // so, scan to see if the phi cycle is actually equal to that value.
10849 {
10850 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10851 // Scan for the first non-phi operand.
10852 while (InValNo != NumOperandVals &&
10853 isa<PHINode>(PN.getIncomingValue(InValNo)))
10854 ++InValNo;
10855
10856 if (InValNo != NumOperandVals) {
10857 Value *NonPhiInVal = PN.getOperand(InValNo);
10858
10859 // Scan the rest of the operands to see if there are any conflicts, if so
10860 // there is no need to recursively scan other phis.
10861 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10862 Value *OpVal = PN.getIncomingValue(InValNo);
10863 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10864 break;
10865 }
10866
10867 // If we scanned over all operands, then we have one unique value plus
10868 // phi values. Scan PHI nodes to see if they all merge in each other or
10869 // the value.
10870 if (InValNo == NumOperandVals) {
10871 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10872 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10873 return ReplaceInstUsesWith(PN, NonPhiInVal);
10874 }
10875 }
10876 }
Chris Lattner60921c92003-12-19 05:58:40 +000010877 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010878}
10879
Chris Lattner7e708292002-06-25 16:13:24 +000010880Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010881 Value *PtrOp = GEP.getOperand(0);
Chris Lattner963f4ba2009-08-30 20:36:46 +000010882 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010883 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010884 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010885
Chris Lattnere87597f2004-10-16 18:11:37 +000010886 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010887 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010888
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010889 bool HasZeroPointerIndex = false;
10890 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10891 HasZeroPointerIndex = C->isNullValue();
10892
10893 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010894 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010895
Chris Lattner28977af2004-04-05 01:30:19 +000010896 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010897 if (TD) {
10898 bool MadeChange = false;
10899 unsigned PtrSize = TD->getPointerSizeInBits();
10900
10901 gep_type_iterator GTI = gep_type_begin(GEP);
10902 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10903 I != E; ++I, ++GTI) {
10904 if (!isa<SequentialType>(*GTI)) continue;
10905
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010906 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010907 // to what we need. If narrower, sign-extend it to what we need. This
10908 // explicit cast can make subsequent optimizations more obvious.
10909 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010910 if (OpBits == PtrSize)
10911 continue;
10912
Chris Lattner2345d1d2009-08-30 20:01:10 +000010913 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010914 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010915 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010916 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010917 }
Chris Lattner28977af2004-04-05 01:30:19 +000010918
Chris Lattner90ac28c2002-08-02 19:29:35 +000010919 // Combine Indices - If the source pointer to this getelementptr instruction
10920 // is a getelementptr instruction, combine the indices of the two
10921 // getelementptr instructions into a single instruction.
10922 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010923 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010924 // Note that if our source is a gep chain itself that we wait for that
10925 // chain to be resolved before we perform this transformation. This
10926 // avoids us creating a TON of code in some cases.
10927 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010928 if (GetElementPtrInst *SrcGEP =
10929 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10930 if (SrcGEP->getNumOperands() == 2)
10931 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010932
Chris Lattner72588fc2007-02-15 22:48:32 +000010933 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010934
10935 // Find out whether the last index in the source GEP is a sequential idx.
10936 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010937 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10938 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010939 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010940
Chris Lattner90ac28c2002-08-02 19:29:35 +000010941 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010942 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010943 // Replace: gep (gep %P, long B), long A, ...
10944 // With: T = long A+B; gep %P, T, ...
10945 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010946 Value *Sum;
10947 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10948 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010949 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010950 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010951 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010952 Sum = SO1;
10953 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010954 // If they aren't the same type, then the input hasn't been processed
10955 // by the loop above yet (which canonicalizes sequential index types to
10956 // intptr_t). Just avoid transforming this until the input has been
10957 // normalized.
10958 if (SO1->getType() != GO1->getType())
10959 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010960 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010961 }
Chris Lattner620ce142004-05-07 22:09:22 +000010962
Chris Lattnerab984842009-08-30 05:30:55 +000010963 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010964 if (Src->getNumOperands() == 2) {
10965 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010966 GEP.setOperand(1, Sum);
10967 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010968 }
Chris Lattnerab984842009-08-30 05:30:55 +000010969 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010970 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010971 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010972 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010973 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010974 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010975 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010976 Indices.append(Src->op_begin()+1, Src->op_end());
10977 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010978 }
10979
Dan Gohmanf8dbee72009-09-07 23:54:19 +000010980 if (!Indices.empty())
10981 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10982 Src->isInBounds()) ?
10983 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10984 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010985 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010986 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010987 }
10988
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010989 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10990 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010991 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000010992
Chris Lattner2de23192009-08-30 20:38:21 +000010993 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10994 // want to change the gep until the bitcasts are eliminated.
10995 if (getBitCastOperand(X)) {
10996 Worklist.AddValue(PtrOp);
10997 return 0;
10998 }
10999
Chris Lattner963f4ba2009-08-30 20:36:46 +000011000 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11001 // into : GEP [10 x i8]* X, i32 0, ...
11002 //
11003 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11004 // into : GEP i8* X, ...
11005 //
11006 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000011007 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000011008 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11009 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011010 if (const ArrayType *CATy =
11011 dyn_cast<ArrayType>(CPTy->getElementType())) {
11012 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11013 if (CATy->getElementType() == XTy->getElementType()) {
11014 // -> GEP i8* X, ...
11015 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011016 return cast<GEPOperator>(&GEP)->isInBounds() ?
11017 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11018 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011019 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11020 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000011021 }
11022
11023 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011024 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011025 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011026 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011027 // At this point, we know that the cast source type is a pointer
11028 // to an array of the same type as the destination pointer
11029 // array. Because the array type is never stepped over (there
11030 // is a leading zero) we can fold the cast into this GEP.
11031 GEP.setOperand(0, X);
11032 return &GEP;
11033 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011034 }
11035 }
Chris Lattnereed48272005-09-13 00:40:14 +000011036 } else if (GEP.getNumOperands() == 2) {
11037 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011038 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11039 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011040 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11041 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011042 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011043 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11044 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011045 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011046 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011047 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011048 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11049 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011050 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011051 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011052 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011053 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011054
11055 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011056 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011057 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011058 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011059
Owen Anderson1d0be152009-08-13 21:58:54 +000011060 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011061 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011062 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011063
11064 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11065 // allow either a mul, shift, or constant here.
11066 Value *NewIdx = 0;
11067 ConstantInt *Scale = 0;
11068 if (ArrayEltSize == 1) {
11069 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011070 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011071 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011072 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011073 Scale = CI;
11074 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11075 if (Inst->getOpcode() == Instruction::Shl &&
11076 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011077 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11078 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011079 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011080 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011081 NewIdx = Inst->getOperand(0);
11082 } else if (Inst->getOpcode() == Instruction::Mul &&
11083 isa<ConstantInt>(Inst->getOperand(1))) {
11084 Scale = cast<ConstantInt>(Inst->getOperand(1));
11085 NewIdx = Inst->getOperand(0);
11086 }
11087 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011088
Chris Lattner7835cdd2005-09-13 18:36:04 +000011089 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011090 // out, perform the transformation. Note, we don't know whether Scale is
11091 // signed or not. We'll use unsigned version of division/modulo
11092 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011093 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011094 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011095 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011096 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011097 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011098 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11099 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011100 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011101 }
11102
11103 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011104 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011105 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011106 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011107 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11108 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11109 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000011110 // The NewGEP must be pointer typed, so must the old one -> BitCast
11111 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011112 }
11113 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011114 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011115 }
Chris Lattner58407792009-01-09 04:53:57 +000011116
Chris Lattner46cd5a12009-01-09 05:44:56 +000011117 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011118 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011119 /// Y = gep X, <...constant indices...>
11120 /// into a gep of the original struct. This is important for SROA and alias
11121 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011122 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011123 if (TD &&
11124 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011125 // Determine how much the GEP moves the pointer. We are guaranteed to get
11126 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011127 ConstantInt *OffsetV =
11128 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011129 int64_t Offset = OffsetV->getSExtValue();
11130
11131 // If this GEP instruction doesn't move the pointer, just replace the GEP
11132 // with a bitcast of the real input to the dest type.
11133 if (Offset == 0) {
11134 // If the bitcast is of an allocation, and the allocation will be
11135 // converted to match the type of the cast, don't touch this.
Victor Hernandez83d63912009-09-18 22:35:49 +000011136 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11137 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011138 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11139 if (Instruction *I = visitBitCast(*BCI)) {
11140 if (I != BCI) {
11141 I->takeName(BCI);
11142 BCI->getParent()->getInstList().insert(BCI, I);
11143 ReplaceInstUsesWith(*BCI, I);
11144 }
11145 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011146 }
Chris Lattner58407792009-01-09 04:53:57 +000011147 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011148 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011149 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011150
11151 // Otherwise, if the offset is non-zero, we need to find out if there is a
11152 // field at Offset in 'A's type. If so, we can pull the cast through the
11153 // GEP.
11154 SmallVector<Value*, 8> NewIndices;
11155 const Type *InTy =
11156 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011157 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011158 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11159 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11160 NewIndices.end()) :
11161 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11162 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011163
11164 if (NGEP->getType() == GEP.getType())
11165 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011166 NGEP->takeName(&GEP);
11167 return new BitCastInst(NGEP, GEP.getType());
11168 }
Chris Lattner58407792009-01-09 04:53:57 +000011169 }
11170 }
11171
Chris Lattner8a2a3112001-12-14 16:52:21 +000011172 return 0;
11173}
11174
Chris Lattner0864acf2002-11-04 16:18:53 +000011175Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11176 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011177 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011178 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11179 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011180 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011181 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011182
11183 // Create and insert the replacement instruction...
11184 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011185 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011186 else {
11187 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011188 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011189 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011190 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011191
Chris Lattner0864acf2002-11-04 16:18:53 +000011192 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011193 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011194 //
11195 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011196 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011197
11198 // Now that I is pointing to the first non-allocation-inst in the block,
11199 // insert our getelementptr instruction...
11200 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011201 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011202 Value *Idx[2];
11203 Idx[0] = NullIdx;
11204 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011205 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11206 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000011207
11208 // Now make everything use the getelementptr instead of the original
11209 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011210 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011211 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011212 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011213 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011214 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011215
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011216 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011217 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011218 // Note that we only do this for alloca's, because malloc should allocate
11219 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011220 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011221 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011222
11223 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11224 if (AI.getAlignment() == 0)
11225 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11226 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011227
Chris Lattner0864acf2002-11-04 16:18:53 +000011228 return 0;
11229}
11230
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011231Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11232 Value *Op = FI.getOperand(0);
11233
Chris Lattner17be6352004-10-18 02:59:09 +000011234 // free undef -> unreachable.
11235 if (isa<UndefValue>(Op)) {
11236 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011237 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011238 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011239 return EraseInstFromFunction(FI);
11240 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011241
Chris Lattner6160e852004-02-28 04:57:37 +000011242 // If we have 'free null' delete the instruction. This can happen in stl code
11243 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011244 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011245 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011246
11247 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11248 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11249 FI.setOperand(0, CI->getOperand(0));
11250 return &FI;
11251 }
11252
11253 // Change free (gep X, 0,0,0,0) into free(X)
11254 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11255 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011256 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011257 FI.setOperand(0, GEPI->getOperand(0));
11258 return &FI;
11259 }
11260 }
11261
11262 // Change free(malloc) into nothing, if the malloc has a single use.
11263 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11264 if (MI->hasOneUse()) {
11265 EraseInstFromFunction(FI);
11266 return EraseInstFromFunction(*MI);
11267 }
Victor Hernandez83d63912009-09-18 22:35:49 +000011268 if (isMalloc(Op)) {
11269 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11270 if (Op->hasOneUse() && CI->hasOneUse()) {
11271 EraseInstFromFunction(FI);
11272 EraseInstFromFunction(*CI);
11273 return EraseInstFromFunction(*cast<Instruction>(Op));
11274 }
11275 } else {
11276 // Op is a call to malloc
11277 if (Op->hasOneUse()) {
11278 EraseInstFromFunction(FI);
11279 return EraseInstFromFunction(*cast<Instruction>(Op));
11280 }
11281 }
11282 }
Chris Lattner6160e852004-02-28 04:57:37 +000011283
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011284 return 0;
11285}
11286
11287
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011288/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011289static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011290 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011291 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011292 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011293 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011294
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011295 if (TD) {
11296 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11297 // Instead of loading constant c string, use corresponding integer value
11298 // directly if string length is small enough.
11299 std::string Str;
11300 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11301 unsigned len = Str.length();
11302 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11303 unsigned numBits = Ty->getPrimitiveSizeInBits();
11304 // Replace LI with immediate integer store.
11305 if ((numBits >> 3) == len + 1) {
11306 APInt StrVal(numBits, 0);
11307 APInt SingleChar(numBits, 0);
11308 if (TD->isLittleEndian()) {
11309 for (signed i = len-1; i >= 0; i--) {
11310 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11311 StrVal = (StrVal << 8) | SingleChar;
11312 }
11313 } else {
11314 for (unsigned i = 0; i < len; i++) {
11315 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11316 StrVal = (StrVal << 8) | SingleChar;
11317 }
11318 // Append NULL at the end.
11319 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011320 StrVal = (StrVal << 8) | SingleChar;
11321 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011322 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011323 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011324 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011325 }
11326 }
11327 }
11328
Mon P Wang6753f952009-02-07 22:19:29 +000011329 const PointerType *DestTy = cast<PointerType>(CI->getType());
11330 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011331 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011332
11333 // If the address spaces don't match, don't eliminate the cast.
11334 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11335 return 0;
11336
Chris Lattnerb89e0712004-07-13 01:49:43 +000011337 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011338
Reid Spencer42230162007-01-22 05:51:25 +000011339 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011340 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011341 // If the source is an array, the code below will not succeed. Check to
11342 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11343 // constants.
11344 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11345 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11346 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011347 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011348 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011349 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011350 SrcTy = cast<PointerType>(CastOp->getType());
11351 SrcPTy = SrcTy->getElementType();
11352 }
11353
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011354 if (IC.getTargetData() &&
11355 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011356 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011357 // Do not allow turning this into a load of an integer, which is then
11358 // casted to a pointer, this pessimizes pointer analysis a lot.
11359 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011360 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11361 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011362
Chris Lattnerf9527852005-01-31 04:50:46 +000011363 // Okay, we are casting from one integer or pointer type to another of
11364 // the same size. Instead of casting the pointer before the load, cast
11365 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011366 Value *NewLoad =
11367 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011368 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011369 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011370 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011371 }
11372 }
11373 return 0;
11374}
11375
Chris Lattner833b8a42003-06-26 05:06:25 +000011376Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11377 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011378
Dan Gohman9941f742007-07-20 16:34:21 +000011379 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011380 if (TD) {
11381 unsigned KnownAlign =
11382 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11383 if (KnownAlign >
11384 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11385 LI.getAlignment()))
11386 LI.setAlignment(KnownAlign);
11387 }
Dan Gohman9941f742007-07-20 16:34:21 +000011388
Chris Lattner963f4ba2009-08-30 20:36:46 +000011389 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011390 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011391 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011392 return Res;
11393
11394 // None of the following transforms are legal for volatile loads.
11395 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011396
Dan Gohman2276a7b2008-10-15 23:19:35 +000011397 // Do really simple store-to-load forwarding and load CSE, to catch cases
11398 // where there are several consequtive memory accesses to the same location,
11399 // separated by a few arithmetic operations.
11400 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011401 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11402 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011403
Christopher Lambb15147e2007-12-29 07:56:53 +000011404 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11405 const Value *GEPI0 = GEPI->getOperand(0);
11406 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011407 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000011408 // Insert a new store to null instruction before the load to indicate
11409 // that this code is not reachable. We do this instead of inserting
11410 // an unreachable instruction directly because we cannot modify the
11411 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011412 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011413 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011414 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011415 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011416 }
Chris Lattner37366c12005-05-01 04:24:53 +000011417
Chris Lattnere87597f2004-10-16 18:11:37 +000011418 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011419 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011420 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000011421 if (isa<UndefValue>(C) ||
11422 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011423 // Insert a new store to null instruction before the load to indicate that
11424 // this code is not reachable. We do this instead of inserting an
11425 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011426 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011427 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011428 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011429 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011430
Chris Lattnere87597f2004-10-16 18:11:37 +000011431 // Instcombine load (constant global) into the value loaded.
11432 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011433 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011434 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011435
Chris Lattnere87597f2004-10-16 18:11:37 +000011436 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011437 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011438 if (CE->getOpcode() == Instruction::GetElementPtr) {
11439 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011440 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011441 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011442 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011443 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011444 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011445 if (CE->getOperand(0)->isNullValue()) {
11446 // Insert a new store to null instruction before the load to indicate
11447 // that this code is not reachable. We do this instead of inserting
11448 // an unreachable instruction directly because we cannot modify the
11449 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011450 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011451 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011452 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011453 }
11454
Reid Spencer3da59db2006-11-27 01:05:10 +000011455 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011456 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011457 return Res;
11458 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011459 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011460 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011461
11462 // If this load comes from anywhere in a constant global, and if the global
11463 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011464 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011465 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011466 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011467 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011468 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011469 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011470 }
11471 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011472
Chris Lattner37366c12005-05-01 04:24:53 +000011473 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011474 // Change select and PHI nodes to select values instead of addresses: this
11475 // helps alias analysis out a lot, allows many others simplifications, and
11476 // exposes redundancy in the code.
11477 //
11478 // Note that we cannot do the transformation unless we know that the
11479 // introduced loads cannot trap! Something like this is valid as long as
11480 // the condition is always false: load (select bool %C, int* null, int* %G),
11481 // but it would not be valid if we transformed it to load from null
11482 // unconditionally.
11483 //
11484 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11485 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011486 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11487 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011488 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11489 SI->getOperand(1)->getName()+".val");
11490 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11491 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011492 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011493 }
11494
Chris Lattner684fe212004-09-23 15:46:00 +000011495 // load (select (cond, null, P)) -> load P
11496 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11497 if (C->isNullValue()) {
11498 LI.setOperand(0, SI->getOperand(2));
11499 return &LI;
11500 }
11501
11502 // load (select (cond, P, null)) -> load P
11503 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11504 if (C->isNullValue()) {
11505 LI.setOperand(0, SI->getOperand(1));
11506 return &LI;
11507 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011508 }
11509 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011510 return 0;
11511}
11512
Reid Spencer55af2b52007-01-19 21:20:31 +000011513/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011514/// when possible. This makes it generally easy to do alias analysis and/or
11515/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011516static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11517 User *CI = cast<User>(SI.getOperand(1));
11518 Value *CastOp = CI->getOperand(0);
11519
11520 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011521 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11522 if (SrcTy == 0) return 0;
11523
11524 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011525
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011526 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11527 return 0;
11528
Chris Lattner3914f722009-01-24 01:00:13 +000011529 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11530 /// to its first element. This allows us to handle things like:
11531 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11532 /// on 32-bit hosts.
11533 SmallVector<Value*, 4> NewGEPIndices;
11534
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011535 // If the source is an array, the code below will not succeed. Check to
11536 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11537 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011538 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11539 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011540 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011541 NewGEPIndices.push_back(Zero);
11542
11543 while (1) {
11544 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011545 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011546 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011547 NewGEPIndices.push_back(Zero);
11548 SrcPTy = STy->getElementType(0);
11549 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11550 NewGEPIndices.push_back(Zero);
11551 SrcPTy = ATy->getElementType();
11552 } else {
11553 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011554 }
Chris Lattner3914f722009-01-24 01:00:13 +000011555 }
11556
Owen Andersondebcb012009-07-29 22:17:13 +000011557 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011558 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011559
11560 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11561 return 0;
11562
Chris Lattner71759c42009-01-16 20:12:52 +000011563 // If the pointers point into different address spaces or if they point to
11564 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011565 if (!IC.getTargetData() ||
11566 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011567 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011568 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11569 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011570 return 0;
11571
11572 // Okay, we are casting from one integer or pointer type to another of
11573 // the same size. Instead of casting the pointer before
11574 // the store, cast the value to be stored.
11575 Value *NewCast;
11576 Value *SIOp0 = SI.getOperand(0);
11577 Instruction::CastOps opcode = Instruction::BitCast;
11578 const Type* CastSrcTy = SIOp0->getType();
11579 const Type* CastDstTy = SrcPTy;
11580 if (isa<PointerType>(CastDstTy)) {
11581 if (CastSrcTy->isInteger())
11582 opcode = Instruction::IntToPtr;
11583 } else if (isa<IntegerType>(CastDstTy)) {
11584 if (isa<PointerType>(SIOp0->getType()))
11585 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011586 }
Chris Lattner3914f722009-01-24 01:00:13 +000011587
11588 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11589 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011590 if (!NewGEPIndices.empty())
11591 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11592 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000011593
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011594 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11595 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011596 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011597}
11598
Chris Lattner4aebaee2008-11-27 08:56:30 +000011599/// equivalentAddressValues - Test if A and B will obviously have the same
11600/// value. This includes recognizing that %t0 and %t1 will have the same
11601/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011602/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011603/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011604/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011605/// %t2 = load i32* %t1
11606///
11607static bool equivalentAddressValues(Value *A, Value *B) {
11608 // Test if the values are trivially equivalent.
11609 if (A == B) return true;
11610
11611 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011612 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11613 // its only used to compare two uses within the same basic block, which
11614 // means that they'll always either have the same value or one of them
11615 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011616 if (isa<BinaryOperator>(A) ||
11617 isa<CastInst>(A) ||
11618 isa<PHINode>(A) ||
11619 isa<GetElementPtrInst>(A))
11620 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011621 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011622 return true;
11623
11624 // Otherwise they may not be equivalent.
11625 return false;
11626}
11627
Dale Johannesen4945c652009-03-03 21:26:39 +000011628// If this instruction has two uses, one of which is a llvm.dbg.declare,
11629// return the llvm.dbg.declare.
11630DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11631 if (!V->hasNUses(2))
11632 return 0;
11633 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11634 UI != E; ++UI) {
11635 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11636 return DI;
11637 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11638 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11639 return DI;
11640 }
11641 }
11642 return 0;
11643}
11644
Chris Lattner2f503e62005-01-31 05:36:43 +000011645Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11646 Value *Val = SI.getOperand(0);
11647 Value *Ptr = SI.getOperand(1);
11648
11649 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011650 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011651 ++NumCombined;
11652 return 0;
11653 }
Chris Lattner836692d2007-01-15 06:51:56 +000011654
11655 // If the RHS is an alloca with a single use, zapify the store, making the
11656 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011657 // If the RHS is an alloca with a two uses, the other one being a
11658 // llvm.dbg.declare, zapify the store and the declare, making the
11659 // alloca dead. We must do this to prevent declare's from affecting
11660 // codegen.
11661 if (!SI.isVolatile()) {
11662 if (Ptr->hasOneUse()) {
11663 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011664 EraseInstFromFunction(SI);
11665 ++NumCombined;
11666 return 0;
11667 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011668 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11669 if (isa<AllocaInst>(GEP->getOperand(0))) {
11670 if (GEP->getOperand(0)->hasOneUse()) {
11671 EraseInstFromFunction(SI);
11672 ++NumCombined;
11673 return 0;
11674 }
11675 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11676 EraseInstFromFunction(*DI);
11677 EraseInstFromFunction(SI);
11678 ++NumCombined;
11679 return 0;
11680 }
11681 }
11682 }
11683 }
11684 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11685 EraseInstFromFunction(*DI);
11686 EraseInstFromFunction(SI);
11687 ++NumCombined;
11688 return 0;
11689 }
Chris Lattner836692d2007-01-15 06:51:56 +000011690 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011691
Dan Gohman9941f742007-07-20 16:34:21 +000011692 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011693 if (TD) {
11694 unsigned KnownAlign =
11695 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11696 if (KnownAlign >
11697 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11698 SI.getAlignment()))
11699 SI.setAlignment(KnownAlign);
11700 }
Dan Gohman9941f742007-07-20 16:34:21 +000011701
Dale Johannesenacb51a32009-03-03 01:43:03 +000011702 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011703 // stores to the same location, separated by a few arithmetic operations. This
11704 // situation often occurs with bitfield accesses.
11705 BasicBlock::iterator BBI = &SI;
11706 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11707 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011708 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011709 // Don't count debug info directives, lest they affect codegen,
11710 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11711 // It is necessary for correctness to skip those that feed into a
11712 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011713 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011714 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011715 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011716 continue;
11717 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011718
11719 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11720 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011721 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11722 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011723 ++NumDeadStore;
11724 ++BBI;
11725 EraseInstFromFunction(*PrevSI);
11726 continue;
11727 }
11728 break;
11729 }
11730
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011731 // If this is a load, we have to stop. However, if the loaded value is from
11732 // the pointer we're loading and is producing the pointer we're storing,
11733 // then *this* store is dead (X = load P; store X -> P).
11734 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011735 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11736 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011737 EraseInstFromFunction(SI);
11738 ++NumCombined;
11739 return 0;
11740 }
11741 // Otherwise, this is a load from some other location. Stores before it
11742 // may not be dead.
11743 break;
11744 }
11745
Chris Lattner9ca96412006-02-08 03:25:32 +000011746 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011747 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011748 break;
11749 }
11750
11751
11752 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011753
11754 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000011755 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011756 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011757 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011758 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011759 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011760 ++NumCombined;
11761 }
11762 return 0; // Do not modify these!
11763 }
11764
11765 // store undef, Ptr -> noop
11766 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011767 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011768 ++NumCombined;
11769 return 0;
11770 }
11771
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011772 // If the pointer destination is a cast, see if we can fold the cast into the
11773 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011774 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011775 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11776 return Res;
11777 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011778 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011779 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11780 return Res;
11781
Chris Lattner408902b2005-09-12 23:23:25 +000011782
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011783 // If this store is the last instruction in the basic block (possibly
11784 // excepting debug info instructions and the pointer bitcasts that feed
11785 // into them), and if the block ends with an unconditional branch, try
11786 // to move it to the successor block.
11787 BBI = &SI;
11788 do {
11789 ++BBI;
11790 } while (isa<DbgInfoIntrinsic>(BBI) ||
11791 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011792 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011793 if (BI->isUnconditional())
11794 if (SimplifyStoreAtEndOfBlock(SI))
11795 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011796
Chris Lattner2f503e62005-01-31 05:36:43 +000011797 return 0;
11798}
11799
Chris Lattner3284d1f2007-04-15 00:07:55 +000011800/// SimplifyStoreAtEndOfBlock - Turn things like:
11801/// if () { *P = v1; } else { *P = v2 }
11802/// into a phi node with a store in the successor.
11803///
Chris Lattner31755a02007-04-15 01:02:18 +000011804/// Simplify things like:
11805/// *P = v1; if () { *P = v2; }
11806/// into a phi node with a store in the successor.
11807///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011808bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11809 BasicBlock *StoreBB = SI.getParent();
11810
11811 // Check to see if the successor block has exactly two incoming edges. If
11812 // so, see if the other predecessor contains a store to the same location.
11813 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011814 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011815
11816 // Determine whether Dest has exactly two predecessors and, if so, compute
11817 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011818 pred_iterator PI = pred_begin(DestBB);
11819 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011820 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011821 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011822 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011823 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011824 return false;
11825
11826 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011827 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011828 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011829 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011830 }
Chris Lattner31755a02007-04-15 01:02:18 +000011831 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011832 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011833
11834 // Bail out if all the relevant blocks aren't distinct (this can happen,
11835 // for example, if SI is in an infinite loop)
11836 if (StoreBB == DestBB || OtherBB == DestBB)
11837 return false;
11838
Chris Lattner31755a02007-04-15 01:02:18 +000011839 // Verify that the other block ends in a branch and is not otherwise empty.
11840 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011841 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011842 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011843 return false;
11844
Chris Lattner31755a02007-04-15 01:02:18 +000011845 // If the other block ends in an unconditional branch, check for the 'if then
11846 // else' case. there is an instruction before the branch.
11847 StoreInst *OtherStore = 0;
11848 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011849 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011850 // Skip over debugging info.
11851 while (isa<DbgInfoIntrinsic>(BBI) ||
11852 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11853 if (BBI==OtherBB->begin())
11854 return false;
11855 --BBI;
11856 }
11857 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011858 OtherStore = dyn_cast<StoreInst>(BBI);
11859 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11860 return false;
11861 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011862 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011863 // destinations is StoreBB, then we have the if/then case.
11864 if (OtherBr->getSuccessor(0) != StoreBB &&
11865 OtherBr->getSuccessor(1) != StoreBB)
11866 return false;
11867
11868 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011869 // if/then triangle. See if there is a store to the same ptr as SI that
11870 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011871 for (;; --BBI) {
11872 // Check to see if we find the matching store.
11873 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11874 if (OtherStore->getOperand(1) != SI.getOperand(1))
11875 return false;
11876 break;
11877 }
Eli Friedman6903a242008-06-13 22:02:12 +000011878 // If we find something that may be using or overwriting the stored
11879 // value, or if we run out of instructions, we can't do the xform.
11880 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011881 BBI == OtherBB->begin())
11882 return false;
11883 }
11884
11885 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011886 // make sure nothing reads or overwrites the stored value in
11887 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011888 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11889 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011890 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011891 return false;
11892 }
11893 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011894
Chris Lattner31755a02007-04-15 01:02:18 +000011895 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011896 Value *MergedVal = OtherStore->getOperand(0);
11897 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011898 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011899 PN->reserveOperandSpace(2);
11900 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011901 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11902 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011903 }
11904
11905 // Advance to a place where it is safe to insert the new store and
11906 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011907 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011908 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11909 OtherStore->isVolatile()), *BBI);
11910
11911 // Nuke the old stores.
11912 EraseInstFromFunction(SI);
11913 EraseInstFromFunction(*OtherStore);
11914 ++NumCombined;
11915 return true;
11916}
11917
Chris Lattner2f503e62005-01-31 05:36:43 +000011918
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011919Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11920 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011921 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011922 BasicBlock *TrueDest;
11923 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011924 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011925 !isa<Constant>(X)) {
11926 // Swap Destinations and condition...
11927 BI.setCondition(X);
11928 BI.setSuccessor(0, FalseDest);
11929 BI.setSuccessor(1, TrueDest);
11930 return &BI;
11931 }
11932
Reid Spencere4d87aa2006-12-23 06:05:41 +000011933 // Cannonicalize fcmp_one -> fcmp_oeq
11934 FCmpInst::Predicate FPred; Value *Y;
11935 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011936 TrueDest, FalseDest)) &&
11937 BI.getCondition()->hasOneUse())
11938 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11939 FPred == FCmpInst::FCMP_OGE) {
11940 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11941 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11942
11943 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011944 BI.setSuccessor(0, FalseDest);
11945 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011946 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011947 return &BI;
11948 }
11949
11950 // Cannonicalize icmp_ne -> icmp_eq
11951 ICmpInst::Predicate IPred;
11952 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011953 TrueDest, FalseDest)) &&
11954 BI.getCondition()->hasOneUse())
11955 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11956 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11957 IPred == ICmpInst::ICMP_SGE) {
11958 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11959 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11960 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011961 BI.setSuccessor(0, FalseDest);
11962 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011963 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011964 return &BI;
11965 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011966
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011967 return 0;
11968}
Chris Lattner0864acf2002-11-04 16:18:53 +000011969
Chris Lattner46238a62004-07-03 00:26:11 +000011970Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11971 Value *Cond = SI.getCondition();
11972 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11973 if (I->getOpcode() == Instruction::Add)
11974 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11975 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11976 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011977 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011978 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011979 AddRHS));
11980 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011981 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011982 return &SI;
11983 }
11984 }
11985 return 0;
11986}
11987
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011988Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011989 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011990
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011991 if (!EV.hasIndices())
11992 return ReplaceInstUsesWith(EV, Agg);
11993
11994 if (Constant *C = dyn_cast<Constant>(Agg)) {
11995 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011996 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011997
11998 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011999 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012000
12001 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12002 // Extract the element indexed by the first index out of the constant
12003 Value *V = C->getOperand(*EV.idx_begin());
12004 if (EV.getNumIndices() > 1)
12005 // Extract the remaining indices out of the constant indexed by the
12006 // first index
12007 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12008 else
12009 return ReplaceInstUsesWith(EV, V);
12010 }
12011 return 0; // Can't handle other constants
12012 }
12013 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12014 // We're extracting from an insertvalue instruction, compare the indices
12015 const unsigned *exti, *exte, *insi, *inse;
12016 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12017 exte = EV.idx_end(), inse = IV->idx_end();
12018 exti != exte && insi != inse;
12019 ++exti, ++insi) {
12020 if (*insi != *exti)
12021 // The insert and extract both reference distinctly different elements.
12022 // This means the extract is not influenced by the insert, and we can
12023 // replace the aggregate operand of the extract with the aggregate
12024 // operand of the insert. i.e., replace
12025 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12026 // %E = extractvalue { i32, { i32 } } %I, 0
12027 // with
12028 // %E = extractvalue { i32, { i32 } } %A, 0
12029 return ExtractValueInst::Create(IV->getAggregateOperand(),
12030 EV.idx_begin(), EV.idx_end());
12031 }
12032 if (exti == exte && insi == inse)
12033 // Both iterators are at the end: Index lists are identical. Replace
12034 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12035 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12036 // with "i32 42"
12037 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12038 if (exti == exte) {
12039 // The extract list is a prefix of the insert list. i.e. replace
12040 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12041 // %E = extractvalue { i32, { i32 } } %I, 1
12042 // with
12043 // %X = extractvalue { i32, { i32 } } %A, 1
12044 // %E = insertvalue { i32 } %X, i32 42, 0
12045 // by switching the order of the insert and extract (though the
12046 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012047 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12048 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000012049 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12050 insi, inse);
12051 }
12052 if (insi == inse)
12053 // The insert list is a prefix of the extract list
12054 // We can simply remove the common indices from the extract and make it
12055 // operate on the inserted value instead of the insertvalue result.
12056 // i.e., replace
12057 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12058 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12059 // with
12060 // %E extractvalue { i32 } { i32 42 }, 0
12061 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12062 exti, exte);
12063 }
12064 // Can't simplify extracts from other values. Note that nested extracts are
12065 // already simplified implicitely by the above (extract ( extract (insert) )
12066 // will be translated into extract ( insert ( extract ) ) first and then just
12067 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012068 return 0;
12069}
12070
Chris Lattner220b0cf2006-03-05 00:22:33 +000012071/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12072/// is to leave as a vector operation.
12073static bool CheapToScalarize(Value *V, bool isConstant) {
12074 if (isa<ConstantAggregateZero>(V))
12075 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012076 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012077 if (isConstant) return true;
12078 // If all elts are the same, we can extract.
12079 Constant *Op0 = C->getOperand(0);
12080 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12081 if (C->getOperand(i) != Op0)
12082 return false;
12083 return true;
12084 }
12085 Instruction *I = dyn_cast<Instruction>(V);
12086 if (!I) return false;
12087
12088 // Insert element gets simplified to the inserted element or is deleted if
12089 // this is constant idx extract element and its a constant idx insertelt.
12090 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12091 isa<ConstantInt>(I->getOperand(2)))
12092 return true;
12093 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12094 return true;
12095 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12096 if (BO->hasOneUse() &&
12097 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12098 CheapToScalarize(BO->getOperand(1), isConstant)))
12099 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012100 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12101 if (CI->hasOneUse() &&
12102 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12103 CheapToScalarize(CI->getOperand(1), isConstant)))
12104 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012105
12106 return false;
12107}
12108
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012109/// Read and decode a shufflevector mask.
12110///
12111/// It turns undef elements into values that are larger than the number of
12112/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012113static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12114 unsigned NElts = SVI->getType()->getNumElements();
12115 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12116 return std::vector<unsigned>(NElts, 0);
12117 if (isa<UndefValue>(SVI->getOperand(2)))
12118 return std::vector<unsigned>(NElts, 2*NElts);
12119
12120 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012121 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012122 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12123 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012124 Result.push_back(NElts*2); // undef -> 8
12125 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012126 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012127 return Result;
12128}
12129
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012130/// FindScalarElement - Given a vector and an element number, see if the scalar
12131/// value is already around as a register, for example if it were inserted then
12132/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012133static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012134 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012135 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12136 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012137 unsigned Width = PTy->getNumElements();
12138 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012139 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012140
12141 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012142 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012143 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012144 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012145 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012146 return CP->getOperand(EltNo);
12147 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12148 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012149 if (!isa<ConstantInt>(III->getOperand(2)))
12150 return 0;
12151 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012152
12153 // If this is an insert to the element we are looking for, return the
12154 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012155 if (EltNo == IIElt)
12156 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012157
12158 // Otherwise, the insertelement doesn't modify the value, recurse on its
12159 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012160 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012161 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012162 unsigned LHSWidth =
12163 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012164 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012165 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012166 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012167 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012168 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012169 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012170 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012171 }
12172
12173 // Otherwise, we don't know.
12174 return 0;
12175}
12176
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012177Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012178 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012179 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012180 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012181
Dan Gohman07a96762007-07-16 14:29:03 +000012182 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012183 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012184 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012185
Reid Spencer9d6565a2007-02-15 02:26:10 +000012186 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012187 // If vector val is constant with all elements the same, replace EI with
12188 // that element. When the elements are not identical, we cannot replace yet
12189 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012190 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012191 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012192 if (C->getOperand(i) != op0) {
12193 op0 = 0;
12194 break;
12195 }
12196 if (op0)
12197 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012198 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012199
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012200 // If extracting a specified index from the vector, see if we can recursively
12201 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012202 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012203 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000012204 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012205
12206 // If this is extracting an invalid index, turn this into undef, to avoid
12207 // crashing the code below.
12208 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012209 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012210
Chris Lattner867b99f2006-10-05 06:55:50 +000012211 // This instruction only demands the single element from the input vector.
12212 // If the input vector has a single use, simplify it based on this use
12213 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012214 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012215 APInt UndefElts(VectorWidth, 0);
12216 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012217 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012218 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012219 EI.setOperand(0, V);
12220 return &EI;
12221 }
12222 }
12223
Owen Andersond672ecb2009-07-03 00:17:18 +000012224 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012225 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012226
12227 // If the this extractelement is directly using a bitcast from a vector of
12228 // the same number of elements, see if we can find the source element from
12229 // it. In this case, we will end up needing to bitcast the scalars.
12230 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12231 if (const VectorType *VT =
12232 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12233 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012234 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12235 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012236 return new BitCastInst(Elt, EI.getType());
12237 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012238 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012239
Chris Lattner73fa49d2006-05-25 22:53:38 +000012240 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000012241 // Push extractelement into predecessor operation if legal and
12242 // profitable to do so
12243 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12244 if (I->hasOneUse() &&
12245 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12246 Value *newEI0 =
12247 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12248 EI.getName()+".lhs");
12249 Value *newEI1 =
12250 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12251 EI.getName()+".rhs");
12252 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012253 }
Chris Lattner275a6d62009-09-08 18:48:01 +000012254 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000012255 // Extracting the inserted element?
12256 if (IE->getOperand(2) == EI.getOperand(1))
12257 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12258 // If the inserted and extracted elements are constants, they must not
12259 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012260 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012261 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012262 EI.setOperand(0, IE->getOperand(0));
12263 return &EI;
12264 }
12265 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12266 // If this is extracting an element from a shufflevector, figure out where
12267 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012268 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12269 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012270 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012271 unsigned LHSWidth =
12272 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12273
12274 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012275 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012276 else if (SrcIdx < LHSWidth*2) {
12277 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012278 Src = SVI->getOperand(1);
12279 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012280 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012281 }
Eric Christophera3500da2009-07-25 02:28:41 +000012282 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012283 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12284 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012285 }
12286 }
Eli Friedman2451a642009-07-18 23:06:53 +000012287 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012288 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012289 return 0;
12290}
12291
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012292/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12293/// elements from either LHS or RHS, return the shuffle mask and true.
12294/// Otherwise, return false.
12295static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012296 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012297 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012298 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12299 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012300 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012301
12302 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012303 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012304 return true;
12305 } else if (V == LHS) {
12306 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012307 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012308 return true;
12309 } else if (V == RHS) {
12310 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012311 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012312 return true;
12313 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12314 // If this is an insert of an extract from some other vector, include it.
12315 Value *VecOp = IEI->getOperand(0);
12316 Value *ScalarOp = IEI->getOperand(1);
12317 Value *IdxOp = IEI->getOperand(2);
12318
Chris Lattnerd929f062006-04-27 21:14:21 +000012319 if (!isa<ConstantInt>(IdxOp))
12320 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012321 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012322
12323 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12324 // Okay, we can handle this if the vector we are insertinting into is
12325 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012326 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012327 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012328 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012329 return true;
12330 }
12331 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12332 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012333 EI->getOperand(0)->getType() == V->getType()) {
12334 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012335 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012336
12337 // This must be extracting from either LHS or RHS.
12338 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12339 // Okay, we can handle this if the vector we are insertinting into is
12340 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012341 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012342 // If so, update the mask to reflect the inserted value.
12343 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012344 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012345 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012346 } else {
12347 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012348 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012349 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012350
12351 }
12352 return true;
12353 }
12354 }
12355 }
12356 }
12357 }
12358 // TODO: Handle shufflevector here!
12359
12360 return false;
12361}
12362
12363/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12364/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12365/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012366static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012367 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012368 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012369 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012370 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012371 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012372
12373 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012374 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012375 return V;
12376 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012377 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012378 return V;
12379 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12380 // If this is an insert of an extract from some other vector, include it.
12381 Value *VecOp = IEI->getOperand(0);
12382 Value *ScalarOp = IEI->getOperand(1);
12383 Value *IdxOp = IEI->getOperand(2);
12384
12385 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12386 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12387 EI->getOperand(0)->getType() == V->getType()) {
12388 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012389 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12390 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012391
12392 // Either the extracted from or inserted into vector must be RHSVec,
12393 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012394 if (EI->getOperand(0) == RHS || RHS == 0) {
12395 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012396 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012397 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012398 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012399 return V;
12400 }
12401
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012402 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012403 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12404 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012405 // Everything but the extracted element is replaced with the RHS.
12406 for (unsigned i = 0; i != NumElts; ++i) {
12407 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012408 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012409 }
12410 return V;
12411 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012412
12413 // If this insertelement is a chain that comes from exactly these two
12414 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012415 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12416 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012417 return EI->getOperand(0);
12418
Chris Lattnerefb47352006-04-15 01:39:45 +000012419 }
12420 }
12421 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012422 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012423
12424 // Otherwise, can't do anything fancy. Return an identity vector.
12425 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012426 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012427 return V;
12428}
12429
12430Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12431 Value *VecOp = IE.getOperand(0);
12432 Value *ScalarOp = IE.getOperand(1);
12433 Value *IdxOp = IE.getOperand(2);
12434
Chris Lattner599ded12007-04-09 01:11:16 +000012435 // Inserting an undef or into an undefined place, remove this.
12436 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12437 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012438
Chris Lattnerefb47352006-04-15 01:39:45 +000012439 // If the inserted element was extracted from some other vector, and if the
12440 // indexes are constant, try to turn this into a shufflevector operation.
12441 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12442 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12443 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012444 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012445 unsigned ExtractedIdx =
12446 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012447 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012448
12449 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12450 return ReplaceInstUsesWith(IE, VecOp);
12451
12452 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012453 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012454
12455 // If we are extracting a value from a vector, then inserting it right
12456 // back into the same place, just use the input vector.
12457 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12458 return ReplaceInstUsesWith(IE, VecOp);
12459
12460 // We could theoretically do this for ANY input. However, doing so could
12461 // turn chains of insertelement instructions into a chain of shufflevector
12462 // instructions, and right now we do not merge shufflevectors. As such,
12463 // only do this in a situation where it is clear that there is benefit.
12464 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12465 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12466 // the values of VecOp, except then one read from EIOp0.
12467 // Build a new shuffle mask.
12468 std::vector<Constant*> Mask;
12469 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012470 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012471 else {
12472 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012473 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012474 NumVectorElts));
12475 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012476 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012477 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012478 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012479 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012480 }
12481
12482 // If this insertelement isn't used by some other insertelement, turn it
12483 // (and any insertelements it points to), into one big shuffle.
12484 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12485 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012486 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012487 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012488 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012489 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012490 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012491 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012492 }
12493 }
12494 }
12495
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012496 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12497 APInt UndefElts(VWidth, 0);
12498 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12499 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12500 return &IE;
12501
Chris Lattnerefb47352006-04-15 01:39:45 +000012502 return 0;
12503}
12504
12505
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012506Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12507 Value *LHS = SVI.getOperand(0);
12508 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012509 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012510
12511 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012512
Chris Lattner867b99f2006-10-05 06:55:50 +000012513 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012514 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012515 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012516
Dan Gohman488fbfc2008-09-09 18:11:14 +000012517 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012518
12519 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12520 return 0;
12521
Evan Cheng388df622009-02-03 10:05:09 +000012522 APInt UndefElts(VWidth, 0);
12523 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12524 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012525 LHS = SVI.getOperand(0);
12526 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012527 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012528 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012529
Chris Lattner863bcff2006-05-25 23:48:38 +000012530 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12531 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12532 if (LHS == RHS || isa<UndefValue>(LHS)) {
12533 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012534 // shuffle(undef,undef,mask) -> undef.
12535 return ReplaceInstUsesWith(SVI, LHS);
12536 }
12537
Chris Lattner863bcff2006-05-25 23:48:38 +000012538 // Remap any references to RHS to use LHS.
12539 std::vector<Constant*> Elts;
12540 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012541 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012542 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012543 else {
12544 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012545 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012546 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012547 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012548 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012549 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012550 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012551 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012552 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012553 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012554 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012555 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012556 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012557 LHS = SVI.getOperand(0);
12558 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012559 MadeChange = true;
12560 }
12561
Chris Lattner7b2e27922006-05-26 00:29:06 +000012562 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012563 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012564
Chris Lattner863bcff2006-05-25 23:48:38 +000012565 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12566 if (Mask[i] >= e*2) continue; // Ignore undef values.
12567 // Is this an identity shuffle of the LHS value?
12568 isLHSID &= (Mask[i] == i);
12569
12570 // Is this an identity shuffle of the RHS value?
12571 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012572 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012573
Chris Lattner863bcff2006-05-25 23:48:38 +000012574 // Eliminate identity shuffles.
12575 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12576 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012577
Chris Lattner7b2e27922006-05-26 00:29:06 +000012578 // If the LHS is a shufflevector itself, see if we can combine it with this
12579 // one without producing an unusual shuffle. Here we are really conservative:
12580 // we are absolutely afraid of producing a shuffle mask not in the input
12581 // program, because the code gen may not be smart enough to turn a merged
12582 // shuffle into two specific shuffles: it may produce worse code. As such,
12583 // we only merge two shuffles if the result is one of the two input shuffle
12584 // masks. In this case, merging the shuffles just removes one instruction,
12585 // which we know is safe. This is good for things like turning:
12586 // (splat(splat)) -> splat.
12587 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12588 if (isa<UndefValue>(RHS)) {
12589 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12590
12591 std::vector<unsigned> NewMask;
12592 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12593 if (Mask[i] >= 2*e)
12594 NewMask.push_back(2*e);
12595 else
12596 NewMask.push_back(LHSMask[Mask[i]]);
12597
12598 // If the result mask is equal to the src shuffle or this shuffle mask, do
12599 // the replacement.
12600 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012601 unsigned LHSInNElts =
12602 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012603 std::vector<Constant*> Elts;
12604 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012605 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012606 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012607 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012608 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012609 }
12610 }
12611 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12612 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012613 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012614 }
12615 }
12616 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012617
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012618 return MadeChange ? &SVI : 0;
12619}
12620
12621
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012622
Chris Lattnerea1c4542004-12-08 23:43:58 +000012623
12624/// TryToSinkInstruction - Try to move the specified instruction from its
12625/// current block into the beginning of DestBlock, which can only happen if it's
12626/// safe to move the instruction past all of the instructions between it and the
12627/// end of its block.
12628static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12629 assert(I->hasOneUse() && "Invariants didn't hold!");
12630
Chris Lattner108e9022005-10-27 17:13:11 +000012631 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012632 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012633 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012634
Chris Lattnerea1c4542004-12-08 23:43:58 +000012635 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012636 if (isa<AllocaInst>(I) && I->getParent() ==
12637 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012638 return false;
12639
Chris Lattner96a52a62004-12-09 07:14:34 +000012640 // We can only sink load instructions if there is nothing between the load and
12641 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012642 if (I->mayReadFromMemory()) {
12643 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012644 Scan != E; ++Scan)
12645 if (Scan->mayWriteToMemory())
12646 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012647 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012648
Dan Gohman02dea8b2008-05-23 21:05:58 +000012649 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012650
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012651 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012652 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012653 ++NumSunkInst;
12654 return true;
12655}
12656
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012657
12658/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12659/// all reachable code to the worklist.
12660///
12661/// This has a couple of tricks to make the code faster and more powerful. In
12662/// particular, we constant fold and DCE instructions as we go, to avoid adding
12663/// them to the worklist (this significantly speeds up instcombine on code where
12664/// many instructions are dead or constant). Additionally, if we find a branch
12665/// whose condition is a known constant, we only visit the reachable successors.
12666///
12667static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012668 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012669 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012670 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012671 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012672 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012673
Chris Lattner2c7718a2007-03-23 19:17:18 +000012674 while (!Worklist.empty()) {
12675 BB = Worklist.back();
12676 Worklist.pop_back();
12677
12678 // We have now visited this block! If we've already been here, ignore it.
12679 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012680
12681 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012682 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12683 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012684
Chris Lattner2c7718a2007-03-23 19:17:18 +000012685 // DCE instruction if trivially dead.
12686 if (isInstructionTriviallyDead(Inst)) {
12687 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012688 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012689 Inst->eraseFromParent();
12690 continue;
12691 }
12692
12693 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012694 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012695 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12696 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012697 Inst->replaceAllUsesWith(C);
12698 ++NumConstProp;
12699 Inst->eraseFromParent();
12700 continue;
12701 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012702
Devang Patel7fe1dec2008-11-19 18:56:50 +000012703 // If there are two consecutive llvm.dbg.stoppoint calls then
12704 // it is likely that the optimizer deleted code in between these
12705 // two intrinsics.
12706 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12707 if (DBI_Next) {
12708 if (DBI_Prev
12709 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12710 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012711 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012712 DBI_Prev->eraseFromParent();
12713 }
12714 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012715 } else {
12716 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012717 }
12718
Chris Lattner7a1e9242009-08-30 06:13:40 +000012719 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012720 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012721
12722 // Recursively visit successors. If this is a branch or switch on a
12723 // constant, only visit the reachable successor.
12724 TerminatorInst *TI = BB->getTerminator();
12725 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12726 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12727 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012728 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012729 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012730 continue;
12731 }
12732 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12733 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12734 // See if this is an explicit destination.
12735 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12736 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012737 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012738 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012739 continue;
12740 }
12741
12742 // Otherwise it is the default destination.
12743 Worklist.push_back(SI->getSuccessor(0));
12744 continue;
12745 }
12746 }
12747
12748 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12749 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012750 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012751}
12752
Chris Lattnerec9c3582007-03-03 02:04:50 +000012753bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012754 MadeIRChange = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012755 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012756
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012757 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12758 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012759
Chris Lattnerb3d59702005-07-07 20:40:38 +000012760 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012761 // Do a depth-first traversal of the function, populate the worklist with
12762 // the reachable instructions. Ignore blocks that are not reachable. Keep
12763 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012764 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012765 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012766
Chris Lattnerb3d59702005-07-07 20:40:38 +000012767 // Do a quick scan over the function. If we find any blocks that are
12768 // unreachable, remove any instructions inside of them. This prevents
12769 // the instcombine code from having to deal with some bad special cases.
12770 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12771 if (!Visited.count(BB)) {
12772 Instruction *Term = BB->getTerminator();
12773 while (Term != BB->begin()) { // Remove instrs bottom-up
12774 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012775
Chris Lattnerbdff5482009-08-23 04:37:46 +000012776 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012777 // A debug intrinsic shouldn't force another iteration if we weren't
12778 // going to do one without it.
12779 if (!isa<DbgInfoIntrinsic>(I)) {
12780 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012781 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000012782 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012783 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012784 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012785 I->eraseFromParent();
12786 }
12787 }
12788 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012789
Chris Lattner873ff012009-08-30 05:55:36 +000012790 while (!Worklist.isEmpty()) {
12791 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012792 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012793
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012794 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012795 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012796 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012797 EraseInstFromFunction(*I);
12798 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012799 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012800 continue;
12801 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012802
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012803 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012804 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012805 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012806
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012807 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012808 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012809 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012810 EraseInstFromFunction(*I);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012811 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012812 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012813 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012814
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012815 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012816 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012817 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12818 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012819 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12820 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012821 if (NewC != CE) {
12822 i->set(NewC);
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012823 MadeIRChange = true;
Chris Lattner1e19d602009-01-31 07:04:22 +000012824 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012825 }
12826
Chris Lattnerea1c4542004-12-08 23:43:58 +000012827 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012828 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012829 BasicBlock *BB = I->getParent();
12830 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12831 if (UserParent != BB) {
12832 bool UserIsSuccessor = false;
12833 // See if the user is one of our successors.
12834 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12835 if (*SI == UserParent) {
12836 UserIsSuccessor = true;
12837 break;
12838 }
12839
12840 // If the user is one of our immediate successors, and if that successor
12841 // only has us as a predecessors (we'd have to split the critical edge
12842 // otherwise), we can keep going.
12843 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12844 next(pred_begin(UserParent)) == pred_end(UserParent))
12845 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012846 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012847 }
12848 }
12849
Chris Lattner74381062009-08-30 07:44:24 +000012850 // Now that we have an instruction, try combining it to simplify it.
12851 Builder->SetInsertPoint(I->getParent(), I);
12852
Reid Spencera9b81012007-03-26 17:44:01 +000012853#ifndef NDEBUG
12854 std::string OrigI;
12855#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012856 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012857
Chris Lattner90ac28c2002-08-02 19:29:35 +000012858 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012859 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012860 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012861 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012862 DEBUG(errs() << "IC: Old = " << *I << '\n'
12863 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012864
Chris Lattnerf523d062004-06-09 05:08:07 +000012865 // Everything uses the new instruction now.
12866 I->replaceAllUsesWith(Result);
12867
12868 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012869 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012870 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012871
Chris Lattner6934a042007-02-11 01:23:03 +000012872 // Move the name to the new instruction first.
12873 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012874
12875 // Insert the new instruction into the basic block...
12876 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012877 BasicBlock::iterator InsertPos = I;
12878
12879 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12880 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12881 ++InsertPos;
12882
12883 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012884
Chris Lattner7a1e9242009-08-30 06:13:40 +000012885 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012886 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012887#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012888 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12889 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012890#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012891
Chris Lattner90ac28c2002-08-02 19:29:35 +000012892 // If the instruction was modified, it's possible that it is now dead.
12893 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012894 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012895 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012896 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012897 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012898 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012899 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012900 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012901 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012902 }
12903 }
12904
Chris Lattner873ff012009-08-30 05:55:36 +000012905 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000012906 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012907}
12908
Chris Lattnerec9c3582007-03-03 02:04:50 +000012909
12910bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012911 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012912 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012913
Chris Lattner74381062009-08-30 07:44:24 +000012914
12915 /// Builder - This is an IRBuilder that automatically inserts new
12916 /// instructions into the worklist when they are created.
12917 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12918 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12919 InstCombineIRInserter(Worklist));
12920 Builder = &TheBuilder;
12921
Chris Lattnerec9c3582007-03-03 02:04:50 +000012922 bool EverMadeChange = false;
12923
12924 // Iterate while there is work to do.
12925 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012926 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012927 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012928
12929 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012930 return EverMadeChange;
12931}
12932
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012933FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012934 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012935}