blob: ea0b6d41a66dd1a98a68fed9d72aea96b57970b3 [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000038#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000040#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000041#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000042#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000043#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000044#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner173234a2008-06-02 01:18:21 +000045#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000046#include "llvm/Target/TargetData.h"
47#include "llvm/Transforms/Utils/BasicBlockUtils.h"
48#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000049#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000050#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000051#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000052#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000053#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000054#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000055#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000056#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000057#include "llvm/Support/PatternMatch.h"
Chris Lattnera4f0b3a2006-08-27 12:54:02 +000058#include "llvm/Support/Compiler.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) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
95 }
96
Chris Lattner3c4e38e2009-08-30 06:27:41 +000097 void AddValue(Value *V) {
98 if (Instruction *I = dyn_cast<Instruction>(V))
99 Add(I);
100 }
101
Chris Lattner7a1e9242009-08-30 06:13:40 +0000102 // Remove - remove I from the worklist if it exists.
Chris Lattner873ff012009-08-30 05:55:36 +0000103 void Remove(Instruction *I) {
104 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105 if (It == WorklistMap.end()) return; // Not in worklist.
106
107 // Don't bother moving everything down, just null out the slot.
108 Worklist[It->second] = 0;
109
110 WorklistMap.erase(It);
111 }
112
113 Instruction *RemoveOne() {
114 Instruction *I = Worklist.back();
115 Worklist.pop_back();
116 WorklistMap.erase(I);
117 return I;
118 }
119
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000120 /// AddUsersToWorkList - When an instruction is simplified, add all users of
121 /// the instruction to the work lists because they might get more simplified
122 /// now.
123 ///
124 void AddUsersToWorkList(Instruction &I) {
125 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
126 UI != UE; ++UI)
127 Add(cast<Instruction>(*UI));
128 }
129
Chris Lattner873ff012009-08-30 05:55:36 +0000130
131 /// Zap - check that the worklist is empty and nuke the backing store for
132 /// the map if it is large.
133 void Zap() {
134 assert(WorklistMap.empty() && "Worklist empty, but map not?");
135
136 // Do an explicit clear, this shrinks the map if needed.
137 WorklistMap.clear();
138 }
139 };
140} // end anonymous namespace.
141
142
143namespace {
Chris Lattner74381062009-08-30 07:44:24 +0000144 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145 /// just like the normal insertion helper, but also adds any new instructions
146 /// to the instcombine worklist.
147 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148 InstCombineWorklist &Worklist;
149 public:
150 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
151
152 void InsertHelper(Instruction *I, const Twine &Name,
153 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
155 Worklist.Add(I);
156 }
157 };
158} // end anonymous namespace
159
160
161namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +0000162 class VISIBILITY_HIDDEN InstCombiner
163 : 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 Lattnerdbab3862007-03-02 21:28:56 +0000167 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000168 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000169 InstCombineWorklist Worklist;
170
Chris Lattner74381062009-08-30 07:44:24 +0000171 /// Builder - This is an IRBuilder that automatically inserts new
172 /// instructions into the worklist when they are created.
173 IRBuilder<true, ConstantFolder, InstCombineIRInserter> *Builder;
174
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000175 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000176 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000177
Owen Andersone922c022009-07-22 00:24:57 +0000178 LLVMContext *Context;
179 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000180
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000181 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000182 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000183
184 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000185
Chris Lattner97e52e42002-04-28 21:27:06 +0000186 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000187 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000188 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000189 }
190
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000191 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000192
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000193 // Visitation implementation - Implement instruction combining for different
194 // instruction types. The semantics are as follows:
195 // Return Value:
196 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000197 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000198 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000199 //
Chris Lattner7e708292002-06-25 16:13:24 +0000200 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000201 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000202 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000203 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000204 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000205 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000206 Instruction *visitURem(BinaryOperator &I);
207 Instruction *visitSRem(BinaryOperator &I);
208 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000209 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000210 Instruction *commonRemTransforms(BinaryOperator &I);
211 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000212 Instruction *commonDivTransforms(BinaryOperator &I);
213 Instruction *commonIDivTransforms(BinaryOperator &I);
214 Instruction *visitUDiv(BinaryOperator &I);
215 Instruction *visitSDiv(BinaryOperator &I);
216 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000217 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000218 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000219 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000220 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000221 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000222 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000223 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitOr (BinaryOperator &I);
225 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000226 Instruction *visitShl(BinaryOperator &I);
227 Instruction *visitAShr(BinaryOperator &I);
228 Instruction *visitLShr(BinaryOperator &I);
229 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000230 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
231 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000232 Instruction *visitFCmpInst(FCmpInst &I);
233 Instruction *visitICmpInst(ICmpInst &I);
234 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000235 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
236 Instruction *LHS,
237 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000238 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
239 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000240
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000241 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000242 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000243 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000244 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000245 Instruction *commonCastTransforms(CastInst &CI);
246 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000247 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000248 Instruction *visitTrunc(TruncInst &CI);
249 Instruction *visitZExt(ZExtInst &CI);
250 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000251 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000252 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000253 Instruction *visitFPToUI(FPToUIInst &FI);
254 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000255 Instruction *visitUIToFP(CastInst &CI);
256 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000257 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000258 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000259 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000260 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
261 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000262 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000263 Instruction *visitSelectInst(SelectInst &SI);
264 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000265 Instruction *visitCallInst(CallInst &CI);
266 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000267 Instruction *visitPHINode(PHINode &PN);
268 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000269 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000270 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000271 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000272 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000273 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000274 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000275 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000276 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000277 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000278 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000279
280 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000281 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000282
Chris Lattner9fe38862003-06-19 17:00:31 +0000283 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000284 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000285 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000286 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000287 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
288 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000289 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000290 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
291
Chris Lattner9fe38862003-06-19 17:00:31 +0000292
Chris Lattner28977af2004-04-05 01:30:19 +0000293 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000294 // InsertNewInstBefore - insert an instruction New before instruction Old
295 // in the program. Add the new instruction to the worklist.
296 //
Chris Lattner955f3312004-09-28 21:48:02 +0000297 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000298 assert(New && New->getParent() == 0 &&
299 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000300 BasicBlock *BB = Old.getParent();
301 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000302 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000303 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000304 }
305
Chris Lattner0c967662004-09-24 15:21:34 +0000306 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
307 /// This also adds the cast to the worklist. Finally, this returns the
308 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000309 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
310 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000311 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000312
Chris Lattnere2ed0572006-04-06 19:19:17 +0000313 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000314 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000315
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000316 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000317 Worklist.Add(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000318 return C;
319 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000320
321 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
322 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
323 }
324
Chris Lattner0c967662004-09-24 15:21:34 +0000325
Chris Lattner8b170942002-08-09 23:47:40 +0000326 // ReplaceInstUsesWith - This method is to be used when an instruction is
327 // found to be dead, replacable with another preexisting expression. Here
328 // we add all uses of I to the worklist, replace all uses of I with the new
329 // value, then return I, so that the inst combiner will know that I was
330 // modified.
331 //
332 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000333 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000334
335 // If we are replacing the instruction with itself, this must be in a
336 // segment of unreachable code, so just clobber the instruction.
337 if (&I == V)
338 V = UndefValue::get(I.getType());
339
340 I.replaceAllUsesWith(V);
341 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000342 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000343
344 // EraseInstFromFunction - When dealing with an instruction that has side
345 // effects or produces a void value, we can't rely on DCE to delete the
346 // instruction. Instead, visit methods should return the value returned by
347 // this function.
348 Instruction *EraseInstFromFunction(Instruction &I) {
349 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000350 // Make sure that we reprocess all operands now that we reduced their
351 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000352 if (I.getNumOperands() < 8) {
353 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
354 if (Instruction *Op = dyn_cast<Instruction>(*i))
355 Worklist.Add(Op);
356 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000357 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000358 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000359 return 0; // Don't do anything with FI
360 }
Chris Lattner173234a2008-06-02 01:18:21 +0000361
362 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
363 APInt &KnownOne, unsigned Depth = 0) const {
364 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
365 }
366
367 bool MaskedValueIsZero(Value *V, const APInt &Mask,
368 unsigned Depth = 0) const {
369 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
370 }
371 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
372 return llvm::ComputeNumSignBits(Op, TD, Depth);
373 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000374
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000375 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000376
Reid Spencere4d87aa2006-12-23 06:05:41 +0000377 /// SimplifyCommutative - This performs a few simplifications for
378 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000379 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000380
Reid Spencere4d87aa2006-12-23 06:05:41 +0000381 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
382 /// most-complex to least-complex order.
383 bool SimplifyCompare(CmpInst &I);
384
Chris Lattner886ab6c2009-01-31 08:15:18 +0000385 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
386 /// based on the demanded bits.
387 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
388 APInt& KnownZero, APInt& KnownOne,
389 unsigned Depth);
390 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000391 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000392 unsigned Depth=0);
393
394 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
395 /// SimplifyDemandedBits knows about. See if the instruction has any
396 /// properties that allow us to simplify its operands.
397 bool SimplifyDemandedInstructionBits(Instruction &Inst);
398
Evan Cheng388df622009-02-03 10:05:09 +0000399 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
400 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000401
Chris Lattner4e998b22004-09-29 05:07:12 +0000402 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
403 // PHI node as operand #0, see if we can fold the instruction into the PHI
404 // (which is only possible if all operands to the PHI are constants).
405 Instruction *FoldOpIntoPhi(Instruction &I);
406
Chris Lattnerbac32862004-11-14 19:13:23 +0000407 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
408 // operator and they all are only used by the PHI, PHI together their
409 // inputs, and do the operation once, to the result of the PHI.
410 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000411 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000412 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
413
Chris Lattner7da52b22006-11-01 04:51:18 +0000414
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000415 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
416 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000417
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000418 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000419 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000420 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000421 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000422 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000423 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000424 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000425 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000426 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000427
Chris Lattnerafe91a52006-06-15 19:07:26 +0000428
Reid Spencerc55b2432006-12-13 18:21:21 +0000429 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000430
Dan Gohman6de29f82009-06-15 22:12:54 +0000431 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000432 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000433 unsigned GetOrEnforceKnownAlignment(Value *V,
434 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000435
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000436 };
Chris Lattner873ff012009-08-30 05:55:36 +0000437} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000438
Dan Gohman844731a2008-05-13 00:00:25 +0000439char InstCombiner::ID = 0;
440static RegisterPass<InstCombiner>
441X("instcombine", "Combine redundant instructions");
442
Chris Lattner4f98c562003-03-10 21:43:22 +0000443// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000444// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000445static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000446 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000447 if (BinaryOperator::isNeg(V) ||
448 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000449 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000450 return 3;
451 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000452 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000453 if (isa<Argument>(V)) return 3;
454 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000455}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000456
Chris Lattnerc8802d22003-03-11 00:12:48 +0000457// isOnlyUse - Return true if this instruction will be deleted if we stop using
458// it.
459static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000460 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000461}
462
Chris Lattner4cb170c2004-02-23 06:38:22 +0000463// getPromotedType - Return the specified type promoted as it would be to pass
464// though a va_arg area...
465static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000466 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
467 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000468 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000469 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000470 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000471}
472
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000473/// getBitCastOperand - If the specified operand is a CastInst, a constant
474/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
475/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000476static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000477 if (Operator *O = dyn_cast<Operator>(V)) {
478 if (O->getOpcode() == Instruction::BitCast)
479 return O->getOperand(0);
480 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
481 if (GEP->hasAllZeroIndices())
482 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000483 }
Chris Lattnereed48272005-09-13 00:40:14 +0000484 return 0;
485}
486
Reid Spencer3da59db2006-11-27 01:05:10 +0000487/// This function is a wrapper around CastInst::isEliminableCastPair. It
488/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000489static Instruction::CastOps
490isEliminableCastPair(
491 const CastInst *CI, ///< The first cast instruction
492 unsigned opcode, ///< The opcode of the second cast instruction
493 const Type *DstTy, ///< The target type for the second cast instruction
494 TargetData *TD ///< The target data for pointer size
495) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000496
Reid Spencer3da59db2006-11-27 01:05:10 +0000497 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
498 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000499
Reid Spencer3da59db2006-11-27 01:05:10 +0000500 // Get the opcodes of the two Cast instructions
501 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
502 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000503
Chris Lattnera0e69692009-03-24 18:35:40 +0000504 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000505 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000506 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000507
508 // We don't want to form an inttoptr or ptrtoint that converts to an integer
509 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000510 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000511 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000512 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000513 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000514 Res = 0;
515
516 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000517}
518
519/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
520/// in any code being generated. It does not require codegen if V is simple
521/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000522static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
523 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000524 if (V->getType() == Ty || isa<Constant>(V)) return false;
525
Chris Lattner01575b72006-05-25 23:24:33 +0000526 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000527 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000528 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000529 return false;
530 return true;
531}
532
Chris Lattner4f98c562003-03-10 21:43:22 +0000533// SimplifyCommutative - This performs a few simplifications for commutative
534// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000535//
Chris Lattner4f98c562003-03-10 21:43:22 +0000536// 1. Order operands such that they are listed from right (least complex) to
537// left (most complex). This puts constants before unary operators before
538// binary operators.
539//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000540// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
541// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000542//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000543bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000544 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000545 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000547
Chris Lattner4f98c562003-03-10 21:43:22 +0000548 if (!I.isAssociative()) return Changed;
549 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000550 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
551 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
552 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000553 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000554 cast<Constant>(I.getOperand(1)),
555 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000556 I.setOperand(0, Op->getOperand(0));
557 I.setOperand(1, Folded);
558 return true;
559 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
560 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
561 isOnlyUse(Op) && isOnlyUse(Op1)) {
562 Constant *C1 = cast<Constant>(Op->getOperand(1));
563 Constant *C2 = cast<Constant>(Op1->getOperand(1));
564
565 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000566 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000567 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000568 Op1->getOperand(0),
569 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000570 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000571 I.setOperand(0, New);
572 I.setOperand(1, Folded);
573 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000574 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000575 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000576 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000577}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000578
Reid Spencere4d87aa2006-12-23 06:05:41 +0000579/// SimplifyCompare - For a CmpInst this function just orders the operands
580/// so that theyare listed from right (least complex) to left (most complex).
581/// This puts constants before unary operators before binary operators.
582bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000583 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000584 return false;
585 I.swapOperands();
586 // Compare instructions are not associative so there's nothing else we can do.
587 return true;
588}
589
Chris Lattner8d969642003-03-10 23:06:50 +0000590// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
591// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000592//
Dan Gohman186a6362009-08-12 16:04:34 +0000593static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000594 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000595 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000596
Chris Lattner0ce85802004-12-14 20:08:06 +0000597 // Constants can be considered to be negated values if they can be folded.
598 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000599 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000600
601 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000603 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000604
Chris Lattner8d969642003-03-10 23:06:50 +0000605 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000606}
607
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000608// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
609// instruction if the LHS is a constant negative zero (which is the 'negate'
610// form).
611//
Dan Gohman186a6362009-08-12 16:04:34 +0000612static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000613 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000614 return BinaryOperator::getFNegArgument(V);
615
616 // Constants can be considered to be negated values if they can be folded.
617 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000618 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000619
620 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
621 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000622 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000623
624 return 0;
625}
626
Dan Gohman186a6362009-08-12 16:04:34 +0000627static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000628 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000629 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000630
631 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000632 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000633 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000634 return 0;
635}
636
Chris Lattnerc8802d22003-03-11 00:12:48 +0000637// dyn_castFoldableMul - If this value is a multiply that can be folded into
638// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000639// non-constant operand of the multiply, and set CST to point to the multiplier.
640// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000641//
Dan Gohman186a6362009-08-12 16:04:34 +0000642static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000643 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000644 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000645 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000646 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000647 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000648 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000649 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000650 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000651 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000652 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000653 CST = ConstantInt::get(V->getType()->getContext(),
654 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000655 return I->getOperand(0);
656 }
657 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000658 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000659}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000660
Reid Spencer7177c3a2007-03-25 05:33:51 +0000661/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000662static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000663 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000664 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000665}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000666/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000667static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000668 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000669 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000670}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000671/// MultiplyOverflows - True if the multiply can not be expressed in an int
672/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000673static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000674 uint32_t W = C1->getBitWidth();
675 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
676 if (sign) {
677 LHSExt.sext(W * 2);
678 RHSExt.sext(W * 2);
679 } else {
680 LHSExt.zext(W * 2);
681 RHSExt.zext(W * 2);
682 }
683
684 APInt MulExt = LHSExt * RHSExt;
685
686 if (sign) {
687 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
688 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
689 return MulExt.slt(Min) || MulExt.sgt(Max);
690 } else
691 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
692}
Chris Lattner955f3312004-09-28 21:48:02 +0000693
Reid Spencere7816b52007-03-08 01:52:58 +0000694
Chris Lattner255d8912006-02-11 09:31:47 +0000695/// ShrinkDemandedConstant - Check to see if the specified operand of the
696/// specified instruction is a constant integer. If so, check to see if there
697/// are any bits set in the constant that are not demanded. If so, shrink the
698/// constant and return true.
699static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000700 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000701 assert(I && "No instruction?");
702 assert(OpNo < I->getNumOperands() && "Operand index too large");
703
704 // If the operand is not a constant integer, nothing to do.
705 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
706 if (!OpC) return false;
707
708 // If there are no bits set that aren't demanded, nothing to do.
709 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
710 if ((~Demanded & OpC->getValue()) == 0)
711 return false;
712
713 // This instruction is producing bits that are not demanded. Shrink the RHS.
714 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000715 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000716 return true;
717}
718
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000719// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
720// set of known zero and one bits, compute the maximum and minimum values that
721// could have the specified known zero and known one bits, returning them in
722// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000723static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000724 const APInt& KnownOne,
725 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000726 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
727 KnownZero.getBitWidth() == Min.getBitWidth() &&
728 KnownZero.getBitWidth() == Max.getBitWidth() &&
729 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000730 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000731
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
733 // bit if it is unknown.
734 Min = KnownOne;
735 Max = KnownOne|UnknownBits;
736
Dan Gohman1c8491e2009-04-25 17:12:48 +0000737 if (UnknownBits.isNegative()) { // Sign bit is unknown
738 Min.set(Min.getBitWidth()-1);
739 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000740 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741}
742
743// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
744// a set of known zero and one bits, compute the maximum and minimum values that
745// could have the specified known zero and known one bits, returning them in
746// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000747static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000748 const APInt &KnownOne,
749 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000750 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
751 KnownZero.getBitWidth() == Min.getBitWidth() &&
752 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000753 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000754 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000755
756 // The minimum value is when the unknown bits are all zeros.
757 Min = KnownOne;
758 // The maximum value is when the unknown bits are all ones.
759 Max = KnownOne|UnknownBits;
760}
Chris Lattner255d8912006-02-11 09:31:47 +0000761
Chris Lattner886ab6c2009-01-31 08:15:18 +0000762/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
763/// SimplifyDemandedBits knows about. See if the instruction has any
764/// properties that allow us to simplify its operands.
765bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000766 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000767 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
768 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
769
770 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
771 KnownZero, KnownOne, 0);
772 if (V == 0) return false;
773 if (V == &Inst) return true;
774 ReplaceInstUsesWith(Inst, V);
775 return true;
776}
777
778/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
779/// specified instruction operand if possible, updating it in place. It returns
780/// true if it made any change and false otherwise.
781bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
782 APInt &KnownZero, APInt &KnownOne,
783 unsigned Depth) {
784 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
785 KnownZero, KnownOne, Depth);
786 if (NewVal == 0) return false;
787 U.set(NewVal);
788 return true;
789}
790
791
792/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
793/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000794/// that only the bits set in DemandedMask of the result of V are ever used
795/// downstream. Consequently, depending on the mask and V, it may be possible
796/// to replace V with a constant or one of its operands. In such cases, this
797/// function does the replacement and returns true. In all other cases, it
798/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000799/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000800/// to be zero in the expression. These are provided to potentially allow the
801/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
802/// the expression. KnownOne and KnownZero always follow the invariant that
803/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
804/// the bits in KnownOne and KnownZero may only be accurate for those bits set
805/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
806/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000807///
808/// This returns null if it did not change anything and it permits no
809/// simplification. This returns V itself if it did some simplification of V's
810/// operands based on the information about what bits are demanded. This returns
811/// some other non-null value if it found out that V is equal to another value
812/// in the context where the specified bits are demanded, but not for all users.
813Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
814 APInt &KnownZero, APInt &KnownOne,
815 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000816 assert(V != 0 && "Null pointer of Value???");
817 assert(Depth <= 6 && "Limit Search Depth");
818 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000819 const Type *VTy = V->getType();
820 assert((TD || !isa<PointerType>(VTy)) &&
821 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000822 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
823 (!VTy->isIntOrIntVector() ||
824 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000825 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000826 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000827 "Value *V, DemandedMask, KnownZero and KnownOne "
828 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000829 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
830 // We know all of the bits for a constant!
831 KnownOne = CI->getValue() & DemandedMask;
832 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000833 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000834 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000835 if (isa<ConstantPointerNull>(V)) {
836 // We know all of the bits for a constant!
837 KnownOne.clear();
838 KnownZero = DemandedMask;
839 return 0;
840 }
841
Chris Lattner08d2cc72009-01-31 07:26:06 +0000842 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000843 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000844 if (DemandedMask == 0) { // Not demanding any bits from V.
845 if (isa<UndefValue>(V))
846 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000847 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000848 }
849
Chris Lattner4598c942009-01-31 08:24:16 +0000850 if (Depth == 6) // Limit search depth.
851 return 0;
852
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000853 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
854 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
855
Dan Gohman1c8491e2009-04-25 17:12:48 +0000856 Instruction *I = dyn_cast<Instruction>(V);
857 if (!I) {
858 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
859 return 0; // Only analyze instructions.
860 }
861
Chris Lattner4598c942009-01-31 08:24:16 +0000862 // If there are multiple uses of this value and we aren't at the root, then
863 // we can't do any simplifications of the operands, because DemandedMask
864 // only reflects the bits demanded by *one* of the users.
865 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000866 // Despite the fact that we can't simplify this instruction in all User's
867 // context, we can at least compute the knownzero/knownone bits, and we can
868 // do simplifications that apply to *just* the one user if we know that
869 // this instruction has a simpler value in that context.
870 if (I->getOpcode() == Instruction::And) {
871 // If either the LHS or the RHS are Zero, the result is zero.
872 ComputeMaskedBits(I->getOperand(1), DemandedMask,
873 RHSKnownZero, RHSKnownOne, Depth+1);
874 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
875 LHSKnownZero, LHSKnownOne, Depth+1);
876
877 // If all of the demanded bits are known 1 on one side, return the other.
878 // These bits cannot contribute to the result of the 'and' in this
879 // context.
880 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
881 (DemandedMask & ~LHSKnownZero))
882 return I->getOperand(0);
883 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
884 (DemandedMask & ~RHSKnownZero))
885 return I->getOperand(1);
886
887 // If all of the demanded bits in the inputs are known zeros, return zero.
888 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000889 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000890
891 } else if (I->getOpcode() == Instruction::Or) {
892 // We can simplify (X|Y) -> X or Y in the user's context if we know that
893 // only bits from X or Y are demanded.
894
895 // If either the LHS or the RHS are One, the result is One.
896 ComputeMaskedBits(I->getOperand(1), DemandedMask,
897 RHSKnownZero, RHSKnownOne, Depth+1);
898 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
899 LHSKnownZero, LHSKnownOne, Depth+1);
900
901 // If all of the demanded bits are known zero on one side, return the
902 // other. These bits cannot contribute to the result of the 'or' in this
903 // context.
904 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
905 (DemandedMask & ~LHSKnownOne))
906 return I->getOperand(0);
907 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
908 (DemandedMask & ~RHSKnownOne))
909 return I->getOperand(1);
910
911 // If all of the potentially set bits on one side are known to be set on
912 // the other side, just use the 'other' side.
913 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
914 (DemandedMask & (~RHSKnownZero)))
915 return I->getOperand(0);
916 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
917 (DemandedMask & (~LHSKnownZero)))
918 return I->getOperand(1);
919 }
920
Chris Lattner4598c942009-01-31 08:24:16 +0000921 // Compute the KnownZero/KnownOne bits to simplify things downstream.
922 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
923 return 0;
924 }
925
926 // If this is the root being simplified, allow it to have multiple uses,
927 // just set the DemandedMask to all bits so that we can try to simplify the
928 // operands. This allows visitTruncInst (for example) to simplify the
929 // operand of a trunc without duplicating all the logic below.
930 if (Depth == 0 && !V->hasOneUse())
931 DemandedMask = APInt::getAllOnesValue(BitWidth);
932
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000934 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000936 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000937 case Instruction::And:
938 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000939 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
940 RHSKnownZero, RHSKnownOne, Depth+1) ||
941 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000942 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 return I;
944 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
945 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000946
947 // If all of the demanded bits are known 1 on one side, return the other.
948 // These bits cannot contribute to the result of the 'and'.
949 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
950 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000951 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000952 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
953 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000954 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000955
956 // If all of the demanded bits in the inputs are known zeros, return zero.
957 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000958 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000961 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000962 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000963
964 // Output known-1 bits are only known if set in both the LHS & RHS.
965 RHSKnownOne &= LHSKnownOne;
966 // Output known-0 are known to be clear if zero in either the LHS | RHS.
967 RHSKnownZero |= LHSKnownZero;
968 break;
969 case Instruction::Or:
970 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000971 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972 RHSKnownZero, RHSKnownOne, Depth+1) ||
973 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000975 return I;
976 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
977 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000978
979 // If all of the demanded bits are known zero on one side, return the other.
980 // These bits cannot contribute to the result of the 'or'.
981 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
982 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000983 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000984 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
985 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987
988 // If all of the potentially set bits on one side are known to be set on
989 // the other side, just use the 'other' side.
990 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
991 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000993 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
994 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000995 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000996
997 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000998 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001000
1001 // Output known-0 bits are only known if clear in both the LHS & RHS.
1002 RHSKnownZero &= LHSKnownZero;
1003 // Output known-1 are known to be set if set in either the LHS | RHS.
1004 RHSKnownOne |= LHSKnownOne;
1005 break;
1006 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001007 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1) ||
1009 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001010 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001011 return I;
1012 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1013 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001014
1015 // If all of the demanded bits are known zero on one side, return the other.
1016 // These bits cannot contribute to the result of the 'xor'.
1017 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001020 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001021
1022 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1023 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1024 (RHSKnownOne & LHSKnownOne);
1025 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1026 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1027 (RHSKnownOne & LHSKnownZero);
1028
1029 // If all of the demanded bits are known to be zero on one side or the
1030 // other, turn this into an *inclusive* or.
1031 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner74381062009-08-30 07:44:24 +00001032 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1033 return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
Reid Spencer8cb68342007-03-12 17:25:59 +00001034
1035 // If all of the demanded bits on one side are known, and all of the set
1036 // bits on that side are also known to be set on the other side, turn this
1037 // into an AND, as we know the bits will be cleared.
1038 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1039 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1040 // all known
1041 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001042 Constant *AndC = Constant::getIntegerValue(VTy,
1043 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001045 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001046 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001047 }
1048 }
1049
1050 // If the RHS is a constant, see if we can simplify it.
1051 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001052 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001054
1055 RHSKnownZero = KnownZeroOut;
1056 RHSKnownOne = KnownOneOut;
1057 break;
1058 }
1059 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001060 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1061 RHSKnownZero, RHSKnownOne, Depth+1) ||
1062 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001063 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001064 return I;
1065 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1066 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001067
1068 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001069 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1070 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001071 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001072
1073 // Only known if known in both the LHS and RHS.
1074 RHSKnownOne &= LHSKnownOne;
1075 RHSKnownZero &= LHSKnownZero;
1076 break;
1077 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001078 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001079 DemandedMask.zext(truncBf);
1080 RHSKnownZero.zext(truncBf);
1081 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001082 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001083 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001084 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001085 DemandedMask.trunc(BitWidth);
1086 RHSKnownZero.trunc(BitWidth);
1087 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001088 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001089 break;
1090 }
1091 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001092 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001093 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001094
1095 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1096 if (const VectorType *SrcVTy =
1097 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1098 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1099 // Don't touch a bitcast between vectors of different element counts.
1100 return false;
1101 } else
1102 // Don't touch a scalar-to-vector bitcast.
1103 return false;
1104 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1105 // Don't touch a vector-to-scalar bitcast.
1106 return false;
1107
Chris Lattner886ab6c2009-01-31 08:15:18 +00001108 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001109 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001110 return I;
1111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001112 break;
1113 case Instruction::ZExt: {
1114 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001115 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001116
Zhou Shengd48653a2007-03-29 04:45:55 +00001117 DemandedMask.trunc(SrcBitWidth);
1118 RHSKnownZero.trunc(SrcBitWidth);
1119 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001120 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001121 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001122 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001123 DemandedMask.zext(BitWidth);
1124 RHSKnownZero.zext(BitWidth);
1125 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001127 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001128 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 break;
1130 }
1131 case Instruction::SExt: {
1132 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001133 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001134
Reid Spencer8cb68342007-03-12 17:25:59 +00001135 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001136 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001137
Zhou Sheng01542f32007-03-29 02:26:30 +00001138 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001139 // If any of the sign extended bits are demanded, we know that the sign
1140 // bit is demanded.
1141 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001142 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001143
Zhou Shengd48653a2007-03-29 04:45:55 +00001144 InputDemandedBits.trunc(SrcBitWidth);
1145 RHSKnownZero.trunc(SrcBitWidth);
1146 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001147 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001148 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001149 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001150 InputDemandedBits.zext(BitWidth);
1151 RHSKnownZero.zext(BitWidth);
1152 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001153 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001154
1155 // If the sign bit of the input is known set or clear, then we know the
1156 // top bits of the result.
1157
1158 // If the input sign bit is known zero, or if the NewBits are not demanded
1159 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001160 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001161 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001162 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1163 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001164 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001165 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 }
1167 break;
1168 }
1169 case Instruction::Add: {
1170 // Figure out what the input bits are. If the top bits of the and result
1171 // are not demanded, then the add doesn't demand them from its input
1172 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001173 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
1175 // If there is a constant on the RHS, there are a variety of xformations
1176 // we can do.
1177 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178 // If null, this should be simplified elsewhere. Some of the xforms here
1179 // won't work if the RHS is zero.
1180 if (RHS->isZero())
1181 break;
1182
1183 // If the top bit of the output is demanded, demand everything from the
1184 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001185 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001186
1187 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001190 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001191
1192 // If the RHS of the add has bits set that can't affect the input, reduce
1193 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001194 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001195 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001196
1197 // Avoid excess work.
1198 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1199 break;
1200
1201 // Turn it into OR if input bits are zero.
1202 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1203 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001204 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001206 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001207 }
1208
1209 // We can say something about the output known-zero and known-one bits,
1210 // depending on potential carries from the input constant and the
1211 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1212 // bits set and the RHS constant is 0x01001, then we know we have a known
1213 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1214
1215 // To compute this, we first compute the potential carry bits. These are
1216 // the bits which may be modified. I'm not aware of a better way to do
1217 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001218 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001219 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001220
1221 // Now that we know which bits have carries, compute the known-1/0 sets.
1222
1223 // Bits are known one if they are known zero in one operand and one in the
1224 // other, and there is no input carry.
1225 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1226 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1227
1228 // Bits are known zero if they are known zero in both operands and there
1229 // is no input carry.
1230 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1231 } else {
1232 // If the high-bits of this ADD are not demanded, then it does not demand
1233 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001234 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001235 // Right fill the mask of bits for this ADD to demand the most
1236 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001237 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001238 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1239 LHSKnownZero, LHSKnownOne, Depth+1) ||
1240 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001242 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001243 }
1244 }
1245 break;
1246 }
1247 case Instruction::Sub:
1248 // If the high-bits of this SUB are not demanded, then it does not demand
1249 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001250 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 // Right fill the mask of bits for this SUB to demand the most
1252 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001253 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001254 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001255 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1256 LHSKnownZero, LHSKnownOne, Depth+1) ||
1257 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001258 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001259 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001260 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001261 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1262 // the known zeros and ones.
1263 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001264 break;
1265 case Instruction::Shl:
1266 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001267 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001268 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001269 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001270 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001271 return I;
1272 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 RHSKnownZero <<= ShiftAmt;
1274 RHSKnownOne <<= ShiftAmt;
1275 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001276 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001277 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001278 }
1279 break;
1280 case Instruction::LShr:
1281 // For a logical shift right
1282 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001283 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001284
Reid Spencer8cb68342007-03-12 17:25:59 +00001285 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001286 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001287 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001288 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001289 return I;
1290 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1292 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001293 if (ShiftAmt) {
1294 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001295 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001296 RHSKnownZero |= HighBits; // high bits known zero.
1297 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 }
1299 break;
1300 case Instruction::AShr:
1301 // If this is an arithmetic shift right and only the low-bit is set, we can
1302 // always convert this into a logical shr, even if the shift amount is
1303 // variable. The low bit of the shift cannot be an input sign bit unless
1304 // the shift amount is >= the size of the datatype, which is undefined.
1305 if (DemandedMask == 1) {
1306 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001310 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001311
1312 // If the sign bit is the only bit demanded by this ashr, then there is no
1313 // need to do it, the shift doesn't change the high bit.
1314 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001315 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001316
1317 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001318 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001319
Reid Spencer8cb68342007-03-12 17:25:59 +00001320 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001321 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001322 // If any of the "high bits" are demanded, we should set the sign bit as
1323 // demanded.
1324 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1325 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001326 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001328 return I;
1329 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001331 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334
1335 // Handle the sign bits.
1336 APInt SignBit(APInt::getSignBit(BitWidth));
1337 // Adjust to where it is now in the mask.
1338 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1339
1340 // If the input sign bit is known to be zero, or if none of the top bits
1341 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001342 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001343 (HighBits & ~DemandedMask) == HighBits) {
1344 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001346 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001347 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1349 RHSKnownOne |= HighBits;
1350 }
1351 }
1352 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353 case Instruction::SRem:
1354 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001355 APInt RA = Rem->getValue().abs();
1356 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001357 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001358 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001359
Nick Lewycky8e394322008-11-02 02:41:50 +00001360 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001361 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001362 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001363 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001364 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001365
1366 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1367 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001368
1369 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001370
Chris Lattner886ab6c2009-01-31 08:15:18 +00001371 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001372 }
1373 }
1374 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001375 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001376 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1377 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001378 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1379 KnownZero2, KnownOne2, Depth+1) ||
1380 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001381 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001382 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001383
Chris Lattner455e9ab2009-01-21 18:09:24 +00001384 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001385 Leaders = std::max(Leaders,
1386 KnownZero2.countLeadingOnes());
1387 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001388 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001389 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001390 case Instruction::Call:
1391 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1392 switch (II->getIntrinsicID()) {
1393 default: break;
1394 case Intrinsic::bswap: {
1395 // If the only bits demanded come from one byte of the bswap result,
1396 // just shift the input byte into position to eliminate the bswap.
1397 unsigned NLZ = DemandedMask.countLeadingZeros();
1398 unsigned NTZ = DemandedMask.countTrailingZeros();
1399
1400 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1401 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1402 // have 14 leading zeros, round to 8.
1403 NLZ &= ~7;
1404 NTZ &= ~7;
1405 // If we need exactly one byte, we can do this transformation.
1406 if (BitWidth-NLZ-NTZ == 8) {
1407 unsigned ResultBit = NTZ;
1408 unsigned InputBit = BitWidth-NTZ-8;
1409
1410 // Replace this with either a left or right shift to get the byte into
1411 // the right place.
1412 Instruction *NewVal;
1413 if (InputBit > ResultBit)
1414 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001415 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001416 else
1417 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001418 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001419 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001420 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001421 }
1422
1423 // TODO: Could compute known zero/one bits based on the input.
1424 break;
1425 }
1426 }
1427 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001428 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001429 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001430 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001431
1432 // If the client is only demanding bits that we know, return the known
1433 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001434 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1435 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001436 return false;
1437}
1438
Chris Lattner867b99f2006-10-05 06:55:50 +00001439
Mon P Wangaeb06d22008-11-10 04:46:22 +00001440/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001441/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001442/// actually used by the caller. This method analyzes which elements of the
1443/// operand are undef and returns that information in UndefElts.
1444///
1445/// If the information about demanded elements can be used to simplify the
1446/// operation, the operation is simplified, then the resultant value is
1447/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001448Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1449 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001450 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001451 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001452 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001453 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001454
1455 if (isa<UndefValue>(V)) {
1456 // If the entire vector is undefined, just return this info.
1457 UndefElts = EltMask;
1458 return 0;
1459 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1460 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001461 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001463
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001465 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1466 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001467 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001468
1469 std::vector<Constant*> Elts;
1470 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001471 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001472 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001473 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001474 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1475 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001476 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 } else { // Otherwise, defined.
1478 Elts.push_back(CP->getOperand(i));
1479 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001480
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001482 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001483 return NewCP != CP ? NewCP : 0;
1484 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001485 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001486 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001487
1488 // Check if this is identity. If so, return 0 since we are not simplifying
1489 // anything.
1490 if (DemandedElts == ((1ULL << VWidth) -1))
1491 return 0;
1492
Reid Spencer9d6565a2007-02-15 02:26:10 +00001493 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001494 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001495 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001496 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001497 for (unsigned i = 0; i != VWidth; ++i) {
1498 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1499 Elts.push_back(Elt);
1500 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001501 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001502 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 }
1504
Dan Gohman488fbfc2008-09-09 18:11:14 +00001505 // Limit search depth.
1506 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001507 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001508
1509 // If multiple users are using the root value, procede with
1510 // simplification conservatively assuming that all elements
1511 // are needed.
1512 if (!V->hasOneUse()) {
1513 // Quit if we find multiple users of a non-root value though.
1514 // They'll be handled when it's their turn to be visited by
1515 // the main instcombine process.
1516 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001517 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001518 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001519
1520 // Conservatively assume that all elements are needed.
1521 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001522 }
1523
1524 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001525 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001526
1527 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001528 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001529 Value *TmpV;
1530 switch (I->getOpcode()) {
1531 default: break;
1532
1533 case Instruction::InsertElement: {
1534 // If this is a variable index, we don't know which element it overwrites.
1535 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001536 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001537 if (Idx == 0) {
1538 // Note that we can't propagate undef elt info, because we don't know
1539 // which elt is getting updated.
1540 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1541 UndefElts2, Depth+1);
1542 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1543 break;
1544 }
1545
1546 // If this is inserting an element that isn't demanded, remove this
1547 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001548 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001549 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1550 Worklist.Add(I);
1551 return I->getOperand(0);
1552 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001553
1554 // Otherwise, the element inserted overwrites whatever was there, so the
1555 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001556 APInt DemandedElts2 = DemandedElts;
1557 DemandedElts2.clear(IdxNo);
1558 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001559 UndefElts, Depth+1);
1560 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1561
1562 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001563 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001564 break;
1565 }
1566 case Instruction::ShuffleVector: {
1567 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001568 uint64_t LHSVWidth =
1569 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001570 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001572 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001573 unsigned MaskVal = Shuffle->getMaskValue(i);
1574 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001575 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001576 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001577 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001578 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001579 else
Evan Cheng388df622009-02-03 10:05:09 +00001580 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001581 }
1582 }
1583 }
1584
Nate Begeman7b254672009-02-11 22:36:25 +00001585 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001587 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001588 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1589
Nate Begeman7b254672009-02-11 22:36:25 +00001590 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1592 UndefElts3, Depth+1);
1593 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1594
1595 bool NewUndefElts = false;
1596 for (unsigned i = 0; i < VWidth; i++) {
1597 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001598 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001599 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001600 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001601 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001602 NewUndefElts = true;
1603 UndefElts.set(i);
1604 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001605 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001606 if (UndefElts3[MaskVal - LHSVWidth]) {
1607 NewUndefElts = true;
1608 UndefElts.set(i);
1609 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001610 }
1611 }
1612
1613 if (NewUndefElts) {
1614 // Add additional discovered undefs.
1615 std::vector<Constant*> Elts;
1616 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001617 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001618 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001619 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001620 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001621 Shuffle->getMaskValue(i)));
1622 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001623 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001624 MadeChange = true;
1625 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001626 break;
1627 }
Chris Lattner69878332007-04-14 22:29:23 +00001628 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001629 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001630 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1631 if (!VTy) break;
1632 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001633 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001634 unsigned Ratio;
1635
1636 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001637 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001638 // elements as are demanded of us.
1639 Ratio = 1;
1640 InputDemandedElts = DemandedElts;
1641 } else if (VWidth > InVWidth) {
1642 // Untested so far.
1643 break;
1644
1645 // If there are more elements in the result than there are in the source,
1646 // then an input element is live if any of the corresponding output
1647 // elements are live.
1648 Ratio = VWidth/InVWidth;
1649 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001650 if (DemandedElts[OutIdx])
1651 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001652 }
1653 } else {
1654 // Untested so far.
1655 break;
1656
1657 // If there are more elements in the source than there are in the result,
1658 // then an input element is live if the corresponding output element is
1659 // live.
1660 Ratio = InVWidth/VWidth;
1661 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001662 if (DemandedElts[InIdx/Ratio])
1663 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001664 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001665
Chris Lattner69878332007-04-14 22:29:23 +00001666 // div/rem demand all inputs, because they don't want divide by zero.
1667 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1668 UndefElts2, Depth+1);
1669 if (TmpV) {
1670 I->setOperand(0, TmpV);
1671 MadeChange = true;
1672 }
1673
1674 UndefElts = UndefElts2;
1675 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001676 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001677 // If there are more elements in the result than there are in the source,
1678 // then an output element is undef if the corresponding input element is
1679 // undef.
1680 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001681 if (UndefElts2[OutIdx/Ratio])
1682 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001683 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001684 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001685 // If there are more elements in the source than there are in the result,
1686 // then a result element is undef if all of the corresponding input
1687 // elements are undef.
1688 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1689 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001690 if (!UndefElts2[InIdx]) // Not undef?
1691 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001692 }
1693 break;
1694 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001695 case Instruction::And:
1696 case Instruction::Or:
1697 case Instruction::Xor:
1698 case Instruction::Add:
1699 case Instruction::Sub:
1700 case Instruction::Mul:
1701 // div/rem demand all inputs, because they don't want divide by zero.
1702 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1703 UndefElts, Depth+1);
1704 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1705 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1706 UndefElts2, Depth+1);
1707 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1708
1709 // Output elements are undefined if both are undefined. Consider things
1710 // like undef&0. The result is known zero, not undef.
1711 UndefElts &= UndefElts2;
1712 break;
1713
1714 case Instruction::Call: {
1715 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1716 if (!II) break;
1717 switch (II->getIntrinsicID()) {
1718 default: break;
1719
1720 // Binary vector operations that work column-wise. A dest element is a
1721 // function of the corresponding input elements from the two inputs.
1722 case Intrinsic::x86_sse_sub_ss:
1723 case Intrinsic::x86_sse_mul_ss:
1724 case Intrinsic::x86_sse_min_ss:
1725 case Intrinsic::x86_sse_max_ss:
1726 case Intrinsic::x86_sse2_sub_sd:
1727 case Intrinsic::x86_sse2_mul_sd:
1728 case Intrinsic::x86_sse2_min_sd:
1729 case Intrinsic::x86_sse2_max_sd:
1730 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1731 UndefElts, Depth+1);
1732 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1733 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1734 UndefElts2, Depth+1);
1735 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1736
1737 // If only the low elt is demanded and this is a scalarizable intrinsic,
1738 // scalarize it now.
1739 if (DemandedElts == 1) {
1740 switch (II->getIntrinsicID()) {
1741 default: break;
1742 case Intrinsic::x86_sse_sub_ss:
1743 case Intrinsic::x86_sse_mul_ss:
1744 case Intrinsic::x86_sse2_sub_sd:
1745 case Intrinsic::x86_sse2_mul_sd:
1746 // TODO: Lower MIN/MAX/ABS/etc
1747 Value *LHS = II->getOperand(1);
1748 Value *RHS = II->getOperand(2);
1749 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001750 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001751 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001752 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001753 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001754
1755 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001756 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001757 case Intrinsic::x86_sse_sub_ss:
1758 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001759 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001760 II->getName()), *II);
1761 break;
1762 case Intrinsic::x86_sse_mul_ss:
1763 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001764 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001765 II->getName()), *II);
1766 break;
1767 }
1768
1769 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001770 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001771 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001772 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001773 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001774 return New;
1775 }
1776 }
1777
1778 // Output elements are undefined if both are undefined. Consider things
1779 // like undef&0. The result is known zero, not undef.
1780 UndefElts &= UndefElts2;
1781 break;
1782 }
1783 break;
1784 }
1785 }
1786 return MadeChange ? I : 0;
1787}
1788
Dan Gohman45b4e482008-05-19 22:14:15 +00001789
Chris Lattner564a7272003-08-13 19:01:45 +00001790/// AssociativeOpt - Perform an optimization on an associative operator. This
1791/// function is designed to check a chain of associative operators for a
1792/// potential to apply a certain optimization. Since the optimization may be
1793/// applicable if the expression was reassociated, this checks the chain, then
1794/// reassociates the expression as necessary to expose the optimization
1795/// opportunity. This makes use of a special Functor, which must define
1796/// 'shouldApply' and 'apply' methods.
1797///
1798template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001799static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001800 unsigned Opcode = Root.getOpcode();
1801 Value *LHS = Root.getOperand(0);
1802
1803 // Quick check, see if the immediate LHS matches...
1804 if (F.shouldApply(LHS))
1805 return F.apply(Root);
1806
1807 // Otherwise, if the LHS is not of the same opcode as the root, return.
1808 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001809 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001810 // Should we apply this transform to the RHS?
1811 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1812
1813 // If not to the RHS, check to see if we should apply to the LHS...
1814 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1815 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1816 ShouldApply = true;
1817 }
1818
1819 // If the functor wants to apply the optimization to the RHS of LHSI,
1820 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1821 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001822 // Now all of the instructions are in the current basic block, go ahead
1823 // and perform the reassociation.
1824 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1825
1826 // First move the selected RHS to the LHS of the root...
1827 Root.setOperand(0, LHSI->getOperand(1));
1828
1829 // Make what used to be the LHS of the root be the user of the root...
1830 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001831 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001832 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001833 return 0;
1834 }
Chris Lattner65725312004-04-16 18:08:07 +00001835 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001836 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001837 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001838 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001839 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001840
1841 // Now propagate the ExtraOperand down the chain of instructions until we
1842 // get to LHSI.
1843 while (TmpLHSI != LHSI) {
1844 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001845 // Move the instruction to immediately before the chain we are
1846 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001847 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001848 ARI = NextLHSI;
1849
Chris Lattner564a7272003-08-13 19:01:45 +00001850 Value *NextOp = NextLHSI->getOperand(1);
1851 NextLHSI->setOperand(1, ExtraOperand);
1852 TmpLHSI = NextLHSI;
1853 ExtraOperand = NextOp;
1854 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001855
Chris Lattner564a7272003-08-13 19:01:45 +00001856 // Now that the instructions are reassociated, have the functor perform
1857 // the transformation...
1858 return F.apply(Root);
1859 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001860
Chris Lattner564a7272003-08-13 19:01:45 +00001861 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1862 }
1863 return 0;
1864}
1865
Dan Gohman844731a2008-05-13 00:00:25 +00001866namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001867
Nick Lewycky02d639f2008-05-23 04:34:58 +00001868// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001869struct AddRHS {
1870 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001871 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001872 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1873 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001874 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001875 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001876 }
1877};
1878
1879// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1880// iff C1&C2 == 0
1881struct AddMaskingAnd {
1882 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001883 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001884 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001885 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001886 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001887 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001888 }
1889 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001890 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001891 }
1892};
1893
Dan Gohman844731a2008-05-13 00:00:25 +00001894}
1895
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001897 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001898 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001899 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001900 }
1901
Chris Lattner2eefe512004-04-09 19:05:30 +00001902 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001903 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1904 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001905
Chris Lattner2eefe512004-04-09 19:05:30 +00001906 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1907 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001908 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1909 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001910 }
1911
1912 Value *Op0 = SO, *Op1 = ConstOperand;
1913 if (!ConstIsRHS)
1914 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001915
Chris Lattner6e7ba452005-01-01 16:22:27 +00001916 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001917 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1918 SO->getName()+".op");
1919 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1920 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1921 SO->getName()+".cmp");
1922 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1923 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1924 SO->getName()+".cmp");
1925 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001926}
1927
1928// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1929// constant as the other operand, try to fold the binary operator into the
1930// select arguments. This also works for Cast instructions, which obviously do
1931// not have a second operand.
1932static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1933 InstCombiner *IC) {
1934 // Don't modify shared select instructions
1935 if (!SI->hasOneUse()) return 0;
1936 Value *TV = SI->getOperand(1);
1937 Value *FV = SI->getOperand(2);
1938
1939 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001940 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001941 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001942
Chris Lattner6e7ba452005-01-01 16:22:27 +00001943 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1944 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1945
Gabor Greif051a9502008-04-06 20:25:17 +00001946 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1947 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001948 }
1949 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001950}
1951
Chris Lattner4e998b22004-09-29 05:07:12 +00001952
1953/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1954/// node as operand #0, see if we can fold the instruction into the PHI (which
1955/// is only possible if all operands to the PHI are constants).
1956Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1957 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001958 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001959 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001960
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001961 // Check to see if all of the operands of the PHI are constants. If there is
1962 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001963 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001964 BasicBlock *NonConstBB = 0;
1965 for (unsigned i = 0; i != NumPHIValues; ++i)
1966 if (!isa<Constant>(PN->getIncomingValue(i))) {
1967 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001968 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001969 NonConstBB = PN->getIncomingBlock(i);
1970
1971 // If the incoming non-constant value is in I's block, we have an infinite
1972 // loop.
1973 if (NonConstBB == I.getParent())
1974 return 0;
1975 }
1976
1977 // If there is exactly one non-constant value, we can insert a copy of the
1978 // operation in that block. However, if this is a critical edge, we would be
1979 // inserting the computation one some other paths (e.g. inside a loop). Only
1980 // do this if the pred block is unconditionally branching into the phi block.
1981 if (NonConstBB) {
1982 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1983 if (!BI || !BI->isUnconditional()) return 0;
1984 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001985
1986 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001987 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001988 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001989 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001990 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001991
1992 // Next, add all of the operands to the PHI.
1993 if (I.getNumOperands() == 2) {
1994 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001995 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001996 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001998 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001999 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002000 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002001 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002002 } else {
2003 assert(PN->getIncomingBlock(i) == NonConstBB);
2004 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002005 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002006 PN->getIncomingValue(i), C, "phitmp",
2007 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002008 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002009 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002010 CI->getPredicate(),
2011 PN->getIncomingValue(i), C, "phitmp",
2012 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002014 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002015
Chris Lattner7a1e9242009-08-30 06:13:40 +00002016 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002017 }
2018 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002019 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002020 } else {
2021 CastInst *CI = cast<CastInst>(&I);
2022 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002023 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002024 Value *InV;
2025 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002026 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002027 } else {
2028 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002029 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002030 I.getType(), "phitmp",
2031 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002032 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002033 }
2034 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002035 }
2036 }
2037 return ReplaceInstUsesWith(I, NewPN);
2038}
2039
Chris Lattner2454a2e2008-01-29 06:52:45 +00002040
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002041/// WillNotOverflowSignedAdd - Return true if we can prove that:
2042/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2043/// This basically requires proving that the add in the original type would not
2044/// overflow to change the sign bit or have a carry out.
2045bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2046 // There are different heuristics we can use for this. Here are some simple
2047 // ones.
2048
2049 // Add has the property that adding any two 2's complement numbers can only
2050 // have one carry bit which can change a sign. As such, if LHS and RHS each
2051 // have at least two sign bits, we know that the addition of the two values will
2052 // sign extend fine.
2053 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2054 return true;
2055
2056
2057 // If one of the operands only has one non-zero bit, and if the other operand
2058 // has a known-zero bit in a more significant place than it (not including the
2059 // sign bit) the ripple may go up to and fill the zero, but won't change the
2060 // sign. For example, (X & ~4) + 1.
2061
2062 // TODO: Implement.
2063
2064 return false;
2065}
2066
Chris Lattner2454a2e2008-01-29 06:52:45 +00002067
Chris Lattner7e708292002-06-25 16:13:24 +00002068Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002069 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002070 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002071
Chris Lattner66331a42004-04-10 22:01:55 +00002072 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002073 // X + undef -> undef
2074 if (isa<UndefValue>(RHS))
2075 return ReplaceInstUsesWith(I, RHS);
2076
Chris Lattner66331a42004-04-10 22:01:55 +00002077 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002078 if (RHSC->isNullValue())
2079 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002080
Chris Lattner66331a42004-04-10 22:01:55 +00002081 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002082 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002083 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002084 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002085 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002086 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002087
2088 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2089 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002090 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002091 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002092
Eli Friedman709b33d2009-07-13 22:27:52 +00002093 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002094 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002095 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002096 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002097 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002098
2099 if (isa<PHINode>(LHS))
2100 if (Instruction *NV = FoldOpIntoPhi(I))
2101 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002102
Chris Lattner4f637d42006-01-06 17:59:59 +00002103 ConstantInt *XorRHS = 0;
2104 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002105 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002106 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002107 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002108 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002109
Zhou Sheng4351c642007-04-02 08:20:41 +00002110 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002111 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2112 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002113 do {
2114 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002115 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2116 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002117 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2118 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002119 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002120 if (!MaskedValueIsZero(XorLHS,
2121 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002122 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002123 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002124 }
2125 }
2126 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002127 C0080Val = APIntOps::lshr(C0080Val, Size);
2128 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2129 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002130
Reid Spencer35c38852007-03-28 01:36:16 +00002131 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002132 // with funny bit widths then this switch statement should be removed. It
2133 // is just here to get the size of the "middle" type back up to something
2134 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002135 const Type *MiddleType = 0;
2136 switch (Size) {
2137 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002138 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2139 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2140 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002141 }
2142 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002143 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002144 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002145 }
2146 }
Chris Lattner66331a42004-04-10 22:01:55 +00002147 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002148
Owen Anderson1d0be152009-08-13 21:58:54 +00002149 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002150 return BinaryOperator::CreateXor(LHS, RHS);
2151
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002152 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002153 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002154 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002155 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002156
2157 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2158 if (RHSI->getOpcode() == Instruction::Sub)
2159 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2160 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2161 }
2162 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2163 if (LHSI->getOpcode() == Instruction::Sub)
2164 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2165 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2166 }
Robert Bocchino71698282004-07-27 21:02:21 +00002167 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002168
Chris Lattner5c4afb92002-05-08 22:46:53 +00002169 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002170 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002171 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002172 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002173 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002174 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002175 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002176 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002177 }
2178
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002179 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002180 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002181
2182 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002183 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002185 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002186
Misha Brukmanfd939082005-04-21 23:48:37 +00002187
Chris Lattner50af16a2004-11-13 19:50:12 +00002188 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002189 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002190 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002191 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002192
2193 // X*C1 + X*C2 --> X * (C1+C2)
2194 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002195 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002196 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002197 }
2198
2199 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002200 if (dyn_castFoldableMul(RHS, C2) == LHS)
2201 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002202
Chris Lattnere617c9e2007-01-05 02:17:46 +00002203 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002204 if (dyn_castNotVal(LHS) == RHS ||
2205 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002206 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002207
Chris Lattnerad3448c2003-02-18 19:57:07 +00002208
Chris Lattner564a7272003-08-13 19:01:45 +00002209 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002210 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2211 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002212 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002213
2214 // A+B --> A|B iff A and B have no bits set in common.
2215 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2216 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2217 APInt LHSKnownOne(IT->getBitWidth(), 0);
2218 APInt LHSKnownZero(IT->getBitWidth(), 0);
2219 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2220 if (LHSKnownZero != 0) {
2221 APInt RHSKnownOne(IT->getBitWidth(), 0);
2222 APInt RHSKnownZero(IT->getBitWidth(), 0);
2223 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2224
2225 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002226 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002227 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002228 }
2229 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002230
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002231 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002232 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002233 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002234 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2235 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002236 if (W != Y) {
2237 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002238 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002239 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002240 std::swap(W, X);
2241 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002242 std::swap(Y, Z);
2243 std::swap(W, X);
2244 }
2245 }
2246
2247 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002248 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002249 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002250 }
2251 }
2252 }
2253
Chris Lattner6b032052003-10-02 15:11:26 +00002254 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002255 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002256 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002257 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002258
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002259 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002260 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002261 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002262 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002263 if (Anded == CRHS) {
2264 // See if all bits from the first bit set in the Add RHS up are included
2265 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002266 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002267
2268 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002269 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002270
2271 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002272 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002273
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002274 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2275 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002276 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002278 }
2279 }
2280 }
2281
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002282 // Try to fold constant add into select arguments.
2283 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002284 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002285 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002286 }
2287
Chris Lattner42790482007-12-20 01:56:58 +00002288 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002289 {
2290 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002291 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002292 if (!SI) {
2293 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002294 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002295 }
Chris Lattner42790482007-12-20 01:56:58 +00002296 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002297 Value *TV = SI->getTrueValue();
2298 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002299 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002300
2301 // Can we fold the add into the argument of the select?
2302 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002303 if (match(FV, m_Zero()) &&
2304 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002305 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002306 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002307 if (match(TV, m_Zero()) &&
2308 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002309 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002310 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002311 }
2312 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002313
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002314 // Check for (add (sext x), y), see if we can merge this into an
2315 // integer add followed by a sext.
2316 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2317 // (add (sext x), cst) --> (sext (add x, cst'))
2318 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2319 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002320 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002321 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002322 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002323 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2324 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002325 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2326 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002327 return new SExtInst(NewAdd, I.getType());
2328 }
2329 }
2330
2331 // (add (sext x), (sext y)) --> (sext (add int x, y))
2332 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2333 // Only do this if x/y have the same type, if at last one of them has a
2334 // single use (so we don't increase the number of sexts), and if the
2335 // integer add will not overflow.
2336 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2337 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2338 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2339 RHSConv->getOperand(0))) {
2340 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002341 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2342 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002343 return new SExtInst(NewAdd, I.getType());
2344 }
2345 }
2346 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002347
2348 return Changed ? &I : 0;
2349}
2350
2351Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2352 bool Changed = SimplifyCommutative(I);
2353 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2354
2355 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2356 // X + 0 --> X
2357 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002358 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002359 (I.getType())->getValueAPF()))
2360 return ReplaceInstUsesWith(I, LHS);
2361 }
2362
2363 if (isa<PHINode>(LHS))
2364 if (Instruction *NV = FoldOpIntoPhi(I))
2365 return NV;
2366 }
2367
2368 // -A + B --> B - A
2369 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002370 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002371 return BinaryOperator::CreateFSub(RHS, LHSV);
2372
2373 // A + -B --> A - B
2374 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002375 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002376 return BinaryOperator::CreateFSub(LHS, V);
2377
2378 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2379 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2380 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2381 return ReplaceInstUsesWith(I, LHS);
2382
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002383 // Check for (add double (sitofp x), y), see if we can merge this into an
2384 // integer add followed by a promotion.
2385 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2386 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2387 // ... if the constant fits in the integer value. This is useful for things
2388 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2389 // requires a constant pool load, and generally allows the add to be better
2390 // instcombined.
2391 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2392 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002393 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002394 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002395 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002396 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2397 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002398 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2399 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002400 return new SIToFPInst(NewAdd, I.getType());
2401 }
2402 }
2403
2404 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2405 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2406 // Only do this if x/y have the same type, if at last one of them has a
2407 // single use (so we don't increase the number of int->fp conversions),
2408 // and if the integer add will not overflow.
2409 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2410 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2411 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2412 RHSConv->getOperand(0))) {
2413 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002414 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2415 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002416 return new SIToFPInst(NewAdd, I.getType());
2417 }
2418 }
2419 }
2420
Chris Lattner7e708292002-06-25 16:13:24 +00002421 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002422}
2423
Chris Lattner7e708292002-06-25 16:13:24 +00002424Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002425 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002426
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002427 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002428 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002429
Chris Lattner233f7dc2002-08-12 21:17:25 +00002430 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002431 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002432 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002433
Chris Lattnere87597f2004-10-16 18:11:37 +00002434 if (isa<UndefValue>(Op0))
2435 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2436 if (isa<UndefValue>(Op1))
2437 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2438
Chris Lattnerd65460f2003-11-05 01:06:05 +00002439 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2440 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002441 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002442 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002443
Chris Lattnerd65460f2003-11-05 01:06:05 +00002444 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002445 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002446 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002447 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002448
Chris Lattner76b7a062007-01-15 07:02:54 +00002449 // -(X >>u 31) -> (X >>s 31)
2450 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002451 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002452 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002453 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002454 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002455 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002456 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002457 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002458 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002459 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002460 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002461 }
2462 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002463 }
2464 else if (SI->getOpcode() == Instruction::AShr) {
2465 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2466 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002467 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002468 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002469 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002470 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002471 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002472 }
2473 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002474 }
2475 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002476 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002477
2478 // Try to fold constant sub into select arguments.
2479 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002480 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002481 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002482
2483 // C - zext(bool) -> bool ? C - 1 : C
2484 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002485 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002486 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002487 }
2488
Owen Anderson1d0be152009-08-13 21:58:54 +00002489 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002490 return BinaryOperator::CreateXor(Op0, Op1);
2491
Chris Lattner43d84d62005-04-07 16:15:25 +00002492 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002493 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002494 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002495 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002496 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002497 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002498 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002499 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002500 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2501 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2502 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002503 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002504 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002505 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002506 }
2507
Chris Lattnerfd059242003-10-15 16:48:29 +00002508 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002509 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2510 // is not used by anyone else...
2511 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002512 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002513 // Swap the two operands of the subexpr...
2514 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2515 Op1I->setOperand(0, IIOp1);
2516 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002517
Chris Lattnera2881962003-02-18 19:28:33 +00002518 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002519 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002520 }
2521
2522 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2523 //
2524 if (Op1I->getOpcode() == Instruction::And &&
2525 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2526 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2527
Chris Lattner74381062009-08-30 07:44:24 +00002528 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002529 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002530 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002531
Reid Spencerac5209e2006-10-16 23:08:08 +00002532 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002533 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002534 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002535 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002536 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002537 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002538 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002539
Chris Lattnerad3448c2003-02-18 19:57:07 +00002540 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002541 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002542 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002543 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002544 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002545 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002546 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002547 }
Chris Lattner40371712002-05-09 01:29:19 +00002548 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002549 }
Chris Lattnera2881962003-02-18 19:28:33 +00002550
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002551 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2552 if (Op0I->getOpcode() == Instruction::Add) {
2553 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2554 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2555 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2556 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2557 } else if (Op0I->getOpcode() == Instruction::Sub) {
2558 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002559 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002560 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002561 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002562 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002563
Chris Lattner50af16a2004-11-13 19:50:12 +00002564 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002565 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002566 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002567 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002568
Chris Lattner50af16a2004-11-13 19:50:12 +00002569 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002570 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002571 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002572 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002573 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002574}
2575
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002576Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2577 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2578
2579 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002580 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002581 return BinaryOperator::CreateFAdd(Op0, V);
2582
2583 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2584 if (Op1I->getOpcode() == Instruction::FAdd) {
2585 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002586 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002587 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002588 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002589 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002590 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002591 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 }
2593
2594 return 0;
2595}
2596
Chris Lattnera0141b92007-07-15 20:42:37 +00002597/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2598/// comparison only checks the sign bit. If it only checks the sign bit, set
2599/// TrueIfSigned if the result of the comparison is true when the input value is
2600/// signed.
2601static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2602 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002603 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002604 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2605 TrueIfSigned = true;
2606 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002607 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2608 TrueIfSigned = true;
2609 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002610 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2611 TrueIfSigned = false;
2612 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002613 case ICmpInst::ICMP_UGT:
2614 // True if LHS u> RHS and RHS == high-bit-mask - 1
2615 TrueIfSigned = true;
2616 return RHS->getValue() ==
2617 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2618 case ICmpInst::ICMP_UGE:
2619 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2620 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002621 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002622 default:
2623 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002624 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002625}
2626
Chris Lattner7e708292002-06-25 16:13:24 +00002627Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002628 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002629 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002630
Eli Friedman1694e092009-07-18 09:12:15 +00002631 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002632 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002633
Chris Lattner233f7dc2002-08-12 21:17:25 +00002634 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002635 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2636 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002637
2638 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002639 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002640 if (SI->getOpcode() == Instruction::Shl)
2641 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002642 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002643 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002644
Zhou Sheng843f07672007-04-19 05:39:12 +00002645 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002646 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2647 if (CI->equalsInt(1)) // X * 1 == X
2648 return ReplaceInstUsesWith(I, Op0);
2649 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002650 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002651
Zhou Sheng97b52c22007-03-29 01:57:21 +00002652 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002653 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002654 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002655 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002656 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002657 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002658 if (Op1->isNullValue())
2659 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002660
2661 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2662 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002663 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002664
2665 // As above, vector X*splat(1.0) -> X in all defined cases.
2666 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002667 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2668 if (CI->equalsInt(1))
2669 return ReplaceInstUsesWith(I, Op0);
2670 }
2671 }
Chris Lattnera2881962003-02-18 19:28:33 +00002672 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002673
2674 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2675 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002676 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002677 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002678 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2679 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002680 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002681
2682 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002683
2684 // Try to fold constant mul into select arguments.
2685 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002686 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002687 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002688
2689 if (isa<PHINode>(Op0))
2690 if (Instruction *NV = FoldOpIntoPhi(I))
2691 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002692 }
2693
Dan Gohman186a6362009-08-12 16:04:34 +00002694 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2695 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002696 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002697
Nick Lewycky0c730792008-11-21 07:33:58 +00002698 // (X / Y) * Y = X - (X % Y)
2699 // (X / Y) * -Y = (X % Y) - X
2700 {
2701 Value *Op1 = I.getOperand(1);
2702 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2703 if (!BO ||
2704 (BO->getOpcode() != Instruction::UDiv &&
2705 BO->getOpcode() != Instruction::SDiv)) {
2706 Op1 = Op0;
2707 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2708 }
Dan Gohman186a6362009-08-12 16:04:34 +00002709 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002710 if (BO && BO->hasOneUse() &&
2711 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2712 (BO->getOpcode() == Instruction::UDiv ||
2713 BO->getOpcode() == Instruction::SDiv)) {
2714 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2715
Dan Gohmanfa94b942009-08-12 16:33:09 +00002716 // If the division is exact, X % Y is zero.
2717 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2718 if (SDiv->isExact()) {
2719 if (Op1BO == Op1)
2720 return ReplaceInstUsesWith(I, Op0BO);
2721 else
2722 return BinaryOperator::CreateNeg(Op0BO);
2723 }
2724
Chris Lattner74381062009-08-30 07:44:24 +00002725 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002726 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002727 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002728 else
Chris Lattner74381062009-08-30 07:44:24 +00002729 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002730 Rem->takeName(BO);
2731
2732 if (Op1BO == Op1)
2733 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002734 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002735 }
2736 }
2737
Owen Anderson1d0be152009-08-13 21:58:54 +00002738 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002739 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2740
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002741 // If one of the operands of the multiply is a cast from a boolean value, then
2742 // we know the bool is either zero or one, so this is a 'masking' multiply.
2743 // See if we can simplify things based on how the boolean was originally
2744 // formed.
2745 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002746 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002747 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002748 BoolCast = CI;
2749 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002750 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002751 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002752 BoolCast = CI;
2753 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002754 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002755 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2756 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002757 bool TIS = false;
2758
Reid Spencere4d87aa2006-12-23 06:05:41 +00002759 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002760 // multiply into a shift/and combination.
2761 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002762 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2763 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002764 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002765 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002766 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002767 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2768 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002769
2770 // If the multiply type is not the same as the source type, sign extend
2771 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002772 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002773 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2774 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002775 Instruction::CastOps opcode =
2776 (SrcBits == DstBits ? Instruction::BitCast :
2777 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2778 V = InsertCastBefore(opcode, V, I.getType(), I);
2779 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002780
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002781 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002782 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002783 }
2784 }
2785 }
2786
Chris Lattner7e708292002-06-25 16:13:24 +00002787 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002788}
2789
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002790Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2791 bool Changed = SimplifyCommutative(I);
2792 Value *Op0 = I.getOperand(0);
2793
2794 // Simplify mul instructions with a constant RHS...
2795 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2796 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2797 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2798 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2799 if (Op1F->isExactlyValue(1.0))
2800 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2801 } else if (isa<VectorType>(Op1->getType())) {
2802 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2803 // As above, vector X*splat(1.0) -> X in all defined cases.
2804 if (Constant *Splat = Op1V->getSplatValue()) {
2805 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2806 if (F->isExactlyValue(1.0))
2807 return ReplaceInstUsesWith(I, Op0);
2808 }
2809 }
2810 }
2811
2812 // Try to fold constant mul into select arguments.
2813 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2814 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2815 return R;
2816
2817 if (isa<PHINode>(Op0))
2818 if (Instruction *NV = FoldOpIntoPhi(I))
2819 return NV;
2820 }
2821
Dan Gohman186a6362009-08-12 16:04:34 +00002822 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2823 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002824 return BinaryOperator::CreateFMul(Op0v, Op1v);
2825
2826 return Changed ? &I : 0;
2827}
2828
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002829/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2830/// instruction.
2831bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2832 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2833
2834 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2835 int NonNullOperand = -1;
2836 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2837 if (ST->isNullValue())
2838 NonNullOperand = 2;
2839 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2840 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2841 if (ST->isNullValue())
2842 NonNullOperand = 1;
2843
2844 if (NonNullOperand == -1)
2845 return false;
2846
2847 Value *SelectCond = SI->getOperand(0);
2848
2849 // Change the div/rem to use 'Y' instead of the select.
2850 I.setOperand(1, SI->getOperand(NonNullOperand));
2851
2852 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2853 // problem. However, the select, or the condition of the select may have
2854 // multiple uses. Based on our knowledge that the operand must be non-zero,
2855 // propagate the known value for the select into other uses of it, and
2856 // propagate a known value of the condition into its other users.
2857
2858 // If the select and condition only have a single use, don't bother with this,
2859 // early exit.
2860 if (SI->use_empty() && SelectCond->hasOneUse())
2861 return true;
2862
2863 // Scan the current block backward, looking for other uses of SI.
2864 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2865
2866 while (BBI != BBFront) {
2867 --BBI;
2868 // If we found a call to a function, we can't assume it will return, so
2869 // information from below it cannot be propagated above it.
2870 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2871 break;
2872
2873 // Replace uses of the select or its condition with the known values.
2874 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2875 I != E; ++I) {
2876 if (*I == SI) {
2877 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002878 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002879 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002880 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2881 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002882 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002883 }
2884 }
2885
2886 // If we past the instruction, quit looking for it.
2887 if (&*BBI == SI)
2888 SI = 0;
2889 if (&*BBI == SelectCond)
2890 SelectCond = 0;
2891
2892 // If we ran out of things to eliminate, break out of the loop.
2893 if (SelectCond == 0 && SI == 0)
2894 break;
2895
2896 }
2897 return true;
2898}
2899
2900
Reid Spencer1628cec2006-10-26 06:15:43 +00002901/// This function implements the transforms on div instructions that work
2902/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2903/// used by the visitors to those instructions.
2904/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002905Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002907
Chris Lattner50b2ca42008-02-19 06:12:18 +00002908 // undef / X -> 0 for integer.
2909 // undef / X -> undef for FP (the undef could be a snan).
2910 if (isa<UndefValue>(Op0)) {
2911 if (Op0->getType()->isFPOrFPVector())
2912 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002913 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002914 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002915
2916 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002917 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002918 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002919
Reid Spencer1628cec2006-10-26 06:15:43 +00002920 return 0;
2921}
Misha Brukmanfd939082005-04-21 23:48:37 +00002922
Reid Spencer1628cec2006-10-26 06:15:43 +00002923/// This function implements the transforms common to both integer division
2924/// instructions (udiv and sdiv). It is called by the visitors to those integer
2925/// division instructions.
2926/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002927Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2929
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002930 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002931 if (Op0 == Op1) {
2932 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002933 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002934 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002935 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002936 }
2937
Owen Andersoneed707b2009-07-24 23:12:02 +00002938 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002939 return ReplaceInstUsesWith(I, CI);
2940 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002941
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 if (Instruction *Common = commonDivTransforms(I))
2943 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002944
2945 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2946 // This does not apply for fdiv.
2947 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2948 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002949
2950 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2951 // div X, 1 == X
2952 if (RHS->equalsInt(1))
2953 return ReplaceInstUsesWith(I, Op0);
2954
2955 // (X / C1) / C2 -> X / (C1*C2)
2956 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2957 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2958 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002959 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002960 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002961 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002962 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002963 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002964 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002965 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002966
Reid Spencerbca0e382007-03-23 20:05:17 +00002967 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002968 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2969 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2970 return R;
2971 if (isa<PHINode>(Op0))
2972 if (Instruction *NV = FoldOpIntoPhi(I))
2973 return NV;
2974 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002975 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002976
Chris Lattnera2881962003-02-18 19:28:33 +00002977 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002978 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002979 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002980 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002981
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002982 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002983 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002984 return ReplaceInstUsesWith(I, Op0);
2985
Nick Lewycky895f0852008-11-27 20:21:08 +00002986 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2987 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2988 // div X, 1 == X
2989 if (X->isOne())
2990 return ReplaceInstUsesWith(I, Op0);
2991 }
2992
Reid Spencer1628cec2006-10-26 06:15:43 +00002993 return 0;
2994}
2995
2996Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2997 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2998
2999 // Handle the integer div common cases
3000 if (Instruction *Common = commonIDivTransforms(I))
3001 return Common;
3002
Reid Spencer1628cec2006-10-26 06:15:43 +00003003 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003004 // X udiv C^2 -> X >> C
3005 // Check to see if this is an unsigned division with an exact power of 2,
3006 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003007 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003008 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003009 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003010
3011 // X udiv C, where C >= signbit
3012 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003013 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003014 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003015 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003016 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003017 }
3018
3019 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003020 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003021 if (RHSI->getOpcode() == Instruction::Shl &&
3022 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003023 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003024 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003025 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003026 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003027 if (uint32_t C2 = C1.logBase2())
3028 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003029 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003030 }
3031 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003032 }
3033
Reid Spencer1628cec2006-10-26 06:15:43 +00003034 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3035 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003036 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003037 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003038 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003039 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003040 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003041 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003042 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003043 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003044 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003045 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003046
3047 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003048 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003049 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003050
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003051 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003052 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003053 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003054 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003055 return 0;
3056}
3057
Reid Spencer1628cec2006-10-26 06:15:43 +00003058Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3059 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3060
3061 // Handle the integer div common cases
3062 if (Instruction *Common = commonIDivTransforms(I))
3063 return Common;
3064
3065 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3066 // sdiv X, -1 == -X
3067 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003068 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003069
Dan Gohmanfa94b942009-08-12 16:33:09 +00003070 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003071 if (cast<SDivOperator>(&I)->isExact() &&
3072 RHS->getValue().isNonNegative() &&
3073 RHS->getValue().isPowerOf2()) {
3074 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3075 RHS->getValue().exactLogBase2());
3076 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3077 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003078
3079 // -X/C --> X/-C provided the negation doesn't overflow.
3080 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3081 if (isa<Constant>(Sub->getOperand(0)) &&
3082 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003083 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003084 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3085 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003086 }
3087
3088 // If the sign bits of both operands are zero (i.e. we can prove they are
3089 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003090 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003091 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003092 if (MaskedValueIsZero(Op0, Mask)) {
3093 if (MaskedValueIsZero(Op1, Mask)) {
3094 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3095 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3096 }
3097 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003098 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003099 ShiftedInt->getValue().isPowerOf2()) {
3100 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3101 // Safe because the only negative value (1 << Y) can take on is
3102 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3103 // the sign bit set.
3104 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3105 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003106 }
Eli Friedman8be17392009-07-18 09:53:21 +00003107 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003108
3109 return 0;
3110}
3111
3112Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3113 return commonDivTransforms(I);
3114}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003115
Reid Spencer0a783f72006-11-02 01:53:59 +00003116/// This function implements the transforms on rem instructions that work
3117/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3118/// is used by the visitors to those instructions.
3119/// @brief Transforms common to all three rem instructions
3120Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003122
Chris Lattner50b2ca42008-02-19 06:12:18 +00003123 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3124 if (I.getType()->isFPOrFPVector())
3125 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003126 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003127 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003128 if (isa<UndefValue>(Op1))
3129 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003130
3131 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003132 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3133 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003134
Reid Spencer0a783f72006-11-02 01:53:59 +00003135 return 0;
3136}
3137
3138/// This function implements the transforms common to both integer remainder
3139/// instructions (urem and srem). It is called by the visitors to those integer
3140/// remainder instructions.
3141/// @brief Common integer remainder transforms
3142Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3144
3145 if (Instruction *common = commonRemTransforms(I))
3146 return common;
3147
Dale Johannesened6af242009-01-21 00:35:19 +00003148 // 0 % X == 0 for integer, we don't need to preserve faults!
3149 if (Constant *LHS = dyn_cast<Constant>(Op0))
3150 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003151 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003152
Chris Lattner857e8cd2004-12-12 21:48:58 +00003153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003154 // X % 0 == undef, we don't need to preserve faults!
3155 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003156 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003157
Chris Lattnera2881962003-02-18 19:28:33 +00003158 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003160
Chris Lattner97943922006-02-28 05:49:21 +00003161 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3162 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3163 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3164 return R;
3165 } else if (isa<PHINode>(Op0I)) {
3166 if (Instruction *NV = FoldOpIntoPhi(I))
3167 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003168 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003169
3170 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003171 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003172 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003173 }
Chris Lattnera2881962003-02-18 19:28:33 +00003174 }
3175
Reid Spencer0a783f72006-11-02 01:53:59 +00003176 return 0;
3177}
3178
3179Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3180 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3181
3182 if (Instruction *common = commonIRemTransforms(I))
3183 return common;
3184
3185 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3186 // X urem C^2 -> X and C
3187 // Check to see if this is an unsigned remainder with an exact power of 2,
3188 // if so, convert to a bitwise and.
3189 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003190 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003191 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003192 }
3193
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003194 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003195 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3196 if (RHSI->getOpcode() == Instruction::Shl &&
3197 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003198 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003199 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003200 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003201 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003202 }
3203 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003204 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003205
Reid Spencer0a783f72006-11-02 01:53:59 +00003206 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3207 // where C1&C2 are powers of two.
3208 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3209 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3210 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3211 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003212 if ((STO->getValue().isPowerOf2()) &&
3213 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003214 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3215 SI->getName()+".t");
3216 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3217 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003218 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003219 }
3220 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003221 }
3222
Chris Lattner3f5b8772002-05-06 16:14:14 +00003223 return 0;
3224}
3225
Reid Spencer0a783f72006-11-02 01:53:59 +00003226Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3227 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3228
Dan Gohmancff55092007-11-05 23:16:33 +00003229 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003230 if (Instruction *Common = commonIRemTransforms(I))
3231 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003232
Dan Gohman186a6362009-08-12 16:04:34 +00003233 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003234 if (!isa<Constant>(RHSNeg) ||
3235 (isa<ConstantInt>(RHSNeg) &&
3236 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003237 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003238 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003239 I.setOperand(1, RHSNeg);
3240 return &I;
3241 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003242
Dan Gohmancff55092007-11-05 23:16:33 +00003243 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003244 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003245 if (I.getType()->isInteger()) {
3246 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3247 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3248 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003249 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003250 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003251 }
3252
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003253 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003254 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3255 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003256
Nick Lewycky9dce8732008-12-20 16:48:00 +00003257 bool hasNegative = false;
3258 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3259 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3260 if (RHS->getValue().isNegative())
3261 hasNegative = true;
3262
3263 if (hasNegative) {
3264 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003265 for (unsigned i = 0; i != VWidth; ++i) {
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3267 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003268 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003269 else
3270 Elts[i] = RHS;
3271 }
3272 }
3273
Owen Andersonaf7ec972009-07-28 21:19:26 +00003274 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003275 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003276 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003277 I.setOperand(1, NewRHSV);
3278 return &I;
3279 }
3280 }
3281 }
3282
Reid Spencer0a783f72006-11-02 01:53:59 +00003283 return 0;
3284}
3285
3286Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003287 return commonRemTransforms(I);
3288}
3289
Chris Lattner457dd822004-06-09 07:59:58 +00003290// isOneBitSet - Return true if there is exactly one bit set in the specified
3291// constant.
3292static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003293 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003294}
3295
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003296// isHighOnes - Return true if the constant is of the form 1+0+.
3297// This is the same as lowones(~X).
3298static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003299 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003300}
3301
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003303/// are carefully arranged to allow folding of expressions such as:
3304///
3305/// (A < B) | (A > B) --> (A != B)
3306///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003307/// Note that this is only valid if the first and second predicates have the
3308/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003309///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003310/// Three bits are used to represent the condition, as follows:
3311/// 0 A > B
3312/// 1 A == B
3313/// 2 A < B
3314///
3315/// <=> Value Definition
3316/// 000 0 Always false
3317/// 001 1 A > B
3318/// 010 2 A == B
3319/// 011 3 A >= B
3320/// 100 4 A < B
3321/// 101 5 A != B
3322/// 110 6 A <= B
3323/// 111 7 Always true
3324///
3325static unsigned getICmpCode(const ICmpInst *ICI) {
3326 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003327 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003328 case ICmpInst::ICMP_UGT: return 1; // 001
3329 case ICmpInst::ICMP_SGT: return 1; // 001
3330 case ICmpInst::ICMP_EQ: return 2; // 010
3331 case ICmpInst::ICMP_UGE: return 3; // 011
3332 case ICmpInst::ICMP_SGE: return 3; // 011
3333 case ICmpInst::ICMP_ULT: return 4; // 100
3334 case ICmpInst::ICMP_SLT: return 4; // 100
3335 case ICmpInst::ICMP_NE: return 5; // 101
3336 case ICmpInst::ICMP_ULE: return 6; // 110
3337 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003338 // True -> 7
3339 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003340 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003341 return 0;
3342 }
3343}
3344
Evan Cheng8db90722008-10-14 17:15:11 +00003345/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3346/// predicate into a three bit mask. It also returns whether it is an ordered
3347/// predicate by reference.
3348static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3349 isOrdered = false;
3350 switch (CC) {
3351 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3352 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003353 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3354 case FCmpInst::FCMP_UGT: return 1; // 001
3355 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3356 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003357 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3358 case FCmpInst::FCMP_UGE: return 3; // 011
3359 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3360 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003361 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3362 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003363 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3364 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003365 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003366 default:
3367 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003368 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003369 return 0;
3370 }
3371}
3372
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373/// getICmpValue - This is the complement of getICmpCode, which turns an
3374/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003375/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003376/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003377static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003378 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003379 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003380 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003381 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003382 case 1:
3383 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003384 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003385 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003386 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3387 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003388 case 3:
3389 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003390 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003391 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003392 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003393 case 4:
3394 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003395 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003396 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003397 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3398 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003399 case 6:
3400 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003401 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003402 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003403 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003404 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003405 }
3406}
3407
Evan Cheng8db90722008-10-14 17:15:11 +00003408/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3409/// opcode and two operands into either a FCmp instruction. isordered is passed
3410/// in to determine which kind of predicate to use in the new fcmp instruction.
3411static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003412 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003413 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003414 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003415 case 0:
3416 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003417 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003418 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003419 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003420 case 1:
3421 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003422 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003423 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003424 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003425 case 2:
3426 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003427 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003428 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003429 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003430 case 3:
3431 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003432 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003433 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003434 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003435 case 4:
3436 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003437 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003438 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003439 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003440 case 5:
3441 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003442 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003443 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003444 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003445 case 6:
3446 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003447 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003448 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003449 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003450 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003451 }
3452}
3453
Chris Lattnerb9553d62008-11-16 04:55:20 +00003454/// PredicatesFoldable - Return true if both predicates match sign or if at
3455/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003456static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3457 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003458 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3459 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460}
3461
3462namespace {
3463// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3464struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003465 InstCombiner &IC;
3466 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003467 ICmpInst::Predicate pred;
3468 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3469 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3470 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003471 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003472 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3473 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003474 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3475 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003476 return false;
3477 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003478 Instruction *apply(Instruction &Log) const {
3479 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3480 if (ICI->getOperand(0) != LHS) {
3481 assert(ICI->getOperand(1) == LHS);
3482 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003483 }
3484
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003485 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003486 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003487 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003488 unsigned Code;
3489 switch (Log.getOpcode()) {
3490 case Instruction::And: Code = LHSCode & RHSCode; break;
3491 case Instruction::Or: Code = LHSCode | RHSCode; break;
3492 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003493 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003494 }
3495
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003496 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3497 ICmpInst::isSignedPredicate(ICI->getPredicate());
3498
Owen Andersond672ecb2009-07-03 00:17:18 +00003499 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003500 if (Instruction *I = dyn_cast<Instruction>(RV))
3501 return I;
3502 // Otherwise, it's a constant boolean value...
3503 return IC.ReplaceInstUsesWith(Log, RV);
3504 }
3505};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003506} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003507
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003508// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3509// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003510// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003511Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003512 ConstantInt *OpRHS,
3513 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003514 BinaryOperator &TheAnd) {
3515 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003516 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003517 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003518 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003519
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520 switch (Op->getOpcode()) {
3521 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003522 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003524 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003525 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003526 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003527 }
3528 break;
3529 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003530 if (Together == AndRHS) // (X | C) & C --> C
3531 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003532
Chris Lattner6e7ba452005-01-01 16:22:27 +00003533 if (Op->hasOneUse() && Together != OpRHS) {
3534 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003535 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003536 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003537 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 }
3539 break;
3540 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003541 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 // Adding a one to a single bit bit-field should be turned into an XOR
3543 // of the bit. First thing to check is to see if this AND is with a
3544 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003545 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003546
3547 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003548 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003549 // Ok, at this point, we know that we are masking the result of the
3550 // ADD down to exactly one bit. If the constant we are adding has
3551 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003552 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003553
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003554 // Check to see if any bits below the one bit set in AndRHSV are set.
3555 if ((AddRHS & (AndRHSV-1)) == 0) {
3556 // If not, the only thing that can effect the output of the AND is
3557 // the bit specified by AndRHSV. If that bit is set, the effect of
3558 // the XOR is to toggle the bit. If it is clear, then the ADD has
3559 // no effect.
3560 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3561 TheAnd.setOperand(0, X);
3562 return &TheAnd;
3563 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003564 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003565 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003566 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003567 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003568 }
3569 }
3570 }
3571 }
3572 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003573
3574 case Instruction::Shl: {
3575 // We know that the AND will not produce any of the bits shifted in, so if
3576 // the anded constant includes them, clear them now!
3577 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003578 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003579 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003580 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003581 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003582
Zhou Sheng290bec52007-03-29 08:15:12 +00003583 if (CI->getValue() == ShlMask) {
3584 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003585 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3586 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003587 TheAnd.setOperand(1, CI);
3588 return &TheAnd;
3589 }
3590 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003591 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003592 case Instruction::LShr:
3593 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003594 // We know that the AND will not produce any of the bits shifted in, so if
3595 // the anded constant includes them, clear them now! This only applies to
3596 // unsigned shifts, because a signed shr may bring in set bits!
3597 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003598 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003599 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003600 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003601 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003602
Zhou Sheng290bec52007-03-29 08:15:12 +00003603 if (CI->getValue() == ShrMask) {
3604 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003605 return ReplaceInstUsesWith(TheAnd, Op);
3606 } else if (CI != AndRHS) {
3607 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3608 return &TheAnd;
3609 }
3610 break;
3611 }
3612 case Instruction::AShr:
3613 // Signed shr.
3614 // See if this is shifting in some sign extension, then masking it out
3615 // with an and.
3616 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003617 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003618 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003619 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003620 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003621 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003622 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003623 // Make the argument unsigned.
3624 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003625 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003626 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003627 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003628 }
3629 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003630 }
3631 return 0;
3632}
3633
Chris Lattner8b170942002-08-09 23:47:40 +00003634
Chris Lattnera96879a2004-09-29 17:40:11 +00003635/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3636/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003637/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3638/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003639/// insert new instructions.
3640Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641 bool isSigned, bool Inside,
3642 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003643 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003644 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003645 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003646
Chris Lattnera96879a2004-09-29 17:40:11 +00003647 if (Inside) {
3648 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003649 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003650
Reid Spencere4d87aa2006-12-23 06:05:41 +00003651 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003652 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003653 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003654 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003655 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 }
3657
3658 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003659 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003660 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003661 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003662 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003663 }
3664
3665 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003666 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003667
Reid Spencere4e40032007-03-21 23:19:50 +00003668 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003669 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003670 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003671 ICmpInst::Predicate pred = (isSigned ?
3672 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003673 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003674 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003675
Reid Spencere4e40032007-03-21 23:19:50 +00003676 // Emit V-Lo >u Hi-1-Lo
3677 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003678 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003679 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003680 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003681 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003682}
3683
Chris Lattner7203e152005-09-18 07:22:02 +00003684// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3685// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3686// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3687// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003688static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003689 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003690 uint32_t BitWidth = Val->getType()->getBitWidth();
3691 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003692
3693 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003694 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003695 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003696 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003697 return true;
3698}
3699
Chris Lattner7203e152005-09-18 07:22:02 +00003700/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3701/// where isSub determines whether the operator is a sub. If we can fold one of
3702/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003703///
3704/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3705/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3706/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707///
3708/// return (A +/- B).
3709///
3710Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003711 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003712 Instruction &I) {
3713 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3714 if (!LHSI || LHSI->getNumOperands() != 2 ||
3715 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3716
3717 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3718
3719 switch (LHSI->getOpcode()) {
3720 default: return 0;
3721 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003722 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003723 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003724 if ((Mask->getValue().countLeadingZeros() +
3725 Mask->getValue().countPopulation()) ==
3726 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003727 break;
3728
3729 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3730 // part, we don't need any explicit masks to take them out of A. If that
3731 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003732 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003733 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003734 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003735 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003736 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003737 break;
3738 }
3739 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003740 return 0;
3741 case Instruction::Or:
3742 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003743 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003744 if ((Mask->getValue().countLeadingZeros() +
3745 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003746 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003747 break;
3748 return 0;
3749 }
3750
Chris Lattnerc8e77562005-09-18 04:24:45 +00003751 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003752 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3753 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003754}
3755
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003756/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3757Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3758 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003759 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003760 ConstantInt *LHSCst, *RHSCst;
3761 ICmpInst::Predicate LHSCC, RHSCC;
3762
Chris Lattnerea065fb2008-11-16 05:10:52 +00003763 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003764 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003765 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003766 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003767 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003768 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003769
3770 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3771 // where C is a power of 2
3772 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3773 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003774 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003775 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003776 }
3777
3778 // From here on, we only handle:
3779 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3780 if (Val != Val2) return 0;
3781
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003782 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3783 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3784 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3785 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3786 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3787 return 0;
3788
3789 // We can't fold (ugt x, C) & (sgt x, C2).
3790 if (!PredicatesFoldable(LHSCC, RHSCC))
3791 return 0;
3792
3793 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003794 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003795 if (ICmpInst::isSignedPredicate(LHSCC) ||
3796 (ICmpInst::isEquality(LHSCC) &&
3797 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003798 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003800 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3801
3802 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003803 std::swap(LHS, RHS);
3804 std::swap(LHSCst, RHSCst);
3805 std::swap(LHSCC, RHSCC);
3806 }
3807
3808 // At this point, we know we have have two icmp instructions
3809 // comparing a value against two constants and and'ing the result
3810 // together. Because of the above check, we know that we only have
3811 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3812 // (from the FoldICmpLogical check above), that the two constants
3813 // are not equal and that the larger constant is on the RHS
3814 assert(LHSCst != RHSCst && "Compares not folded above?");
3815
3816 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003817 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003818 case ICmpInst::ICMP_EQ:
3819 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003820 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003821 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3822 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3823 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003824 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3826 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3827 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3828 return ReplaceInstUsesWith(I, LHS);
3829 }
3830 case ICmpInst::ICMP_NE:
3831 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003832 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003833 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003834 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003835 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003836 break; // (X != 13 & X u< 15) -> no change
3837 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003838 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003839 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003840 break; // (X != 13 & X s< 15) -> no change
3841 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3842 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3843 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3844 return ReplaceInstUsesWith(I, RHS);
3845 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003846 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003847 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003848 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003849 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003850 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003851 }
3852 break; // (X != 13 & X != 15) -> no change
3853 }
3854 break;
3855 case ICmpInst::ICMP_ULT:
3856 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003857 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003858 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3859 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003860 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003861 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3862 break;
3863 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3864 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3865 return ReplaceInstUsesWith(I, LHS);
3866 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3867 break;
3868 }
3869 break;
3870 case ICmpInst::ICMP_SLT:
3871 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003872 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003873 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3874 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003875 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003876 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3877 break;
3878 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3879 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3880 return ReplaceInstUsesWith(I, LHS);
3881 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3882 break;
3883 }
3884 break;
3885 case ICmpInst::ICMP_UGT:
3886 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003887 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003888 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3889 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3890 return ReplaceInstUsesWith(I, RHS);
3891 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3892 break;
3893 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003894 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003895 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003896 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003897 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003898 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003899 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003900 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3901 break;
3902 }
3903 break;
3904 case ICmpInst::ICMP_SGT:
3905 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003906 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003907 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3908 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3909 return ReplaceInstUsesWith(I, RHS);
3910 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3911 break;
3912 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003913 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003914 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003915 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003916 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003917 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003918 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003919 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3920 break;
3921 }
3922 break;
3923 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003924
3925 return 0;
3926}
3927
Chris Lattner42d1be02009-07-23 05:14:02 +00003928Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3929 FCmpInst *RHS) {
3930
3931 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3932 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3933 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3934 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3935 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3936 // If either of the constants are nans, then the whole thing returns
3937 // false.
3938 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003939 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003940 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003941 LHS->getOperand(0), RHS->getOperand(0));
3942 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003943
3944 // Handle vector zeros. This occurs because the canonical form of
3945 // "fcmp ord x,x" is "fcmp ord x, 0".
3946 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3947 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003948 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003949 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003950 return 0;
3951 }
3952
3953 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3954 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3955 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3956
3957
3958 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3959 // Swap RHS operands to match LHS.
3960 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3961 std::swap(Op1LHS, Op1RHS);
3962 }
3963
3964 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3965 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3966 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003967 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003968
3969 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003970 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003971 if (Op0CC == FCmpInst::FCMP_TRUE)
3972 return ReplaceInstUsesWith(I, RHS);
3973 if (Op1CC == FCmpInst::FCMP_TRUE)
3974 return ReplaceInstUsesWith(I, LHS);
3975
3976 bool Op0Ordered;
3977 bool Op1Ordered;
3978 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3979 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3980 if (Op1Pred == 0) {
3981 std::swap(LHS, RHS);
3982 std::swap(Op0Pred, Op1Pred);
3983 std::swap(Op0Ordered, Op1Ordered);
3984 }
3985 if (Op0Pred == 0) {
3986 // uno && ueq -> uno && (uno || eq) -> ueq
3987 // ord && olt -> ord && (ord && lt) -> olt
3988 if (Op0Ordered == Op1Ordered)
3989 return ReplaceInstUsesWith(I, RHS);
3990
3991 // uno && oeq -> uno && (ord && eq) -> false
3992 // uno && ord -> false
3993 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003994 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003995 // ord && ueq -> ord && (uno || eq) -> oeq
3996 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3997 Op0LHS, Op0RHS, Context));
3998 }
3999 }
4000
4001 return 0;
4002}
4003
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004004
Chris Lattner7e708292002-06-25 16:13:24 +00004005Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004006 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004007 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004008
Chris Lattnere87597f2004-10-16 18:11:37 +00004009 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004010 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004011
Chris Lattner6e7ba452005-01-01 16:22:27 +00004012 // and X, X = X
4013 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004014 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004015
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004016 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004017 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004018 if (SimplifyDemandedInstructionBits(I))
4019 return &I;
4020 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004021 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004022 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004023 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004024 } else if (isa<ConstantAggregateZero>(Op1)) {
4025 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004026 }
4027 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004028
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004029 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004030 const APInt& AndRHSMask = AndRHS->getValue();
4031 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004032
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004033 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004034 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004035 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004036 Value *Op0LHS = Op0I->getOperand(0);
4037 Value *Op0RHS = Op0I->getOperand(1);
4038 switch (Op0I->getOpcode()) {
4039 case Instruction::Xor:
4040 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004041 // If the mask is only needed on one incoming arm, push it up.
4042 if (Op0I->hasOneUse()) {
4043 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4044 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004045 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4046 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004047 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004048 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004049 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004050 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004051 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4052 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004053 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4054 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004055 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004056 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4057 }
4058 }
4059
Chris Lattner6e7ba452005-01-01 16:22:27 +00004060 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004061 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004062 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4063 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4064 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4065 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004066 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004067 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004068 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004069 break;
4070
4071 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004072 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4073 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4074 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4075 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004076 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004077
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004078 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4079 // has 1's for all bits that the subtraction with A might affect.
4080 if (Op0I->hasOneUse()) {
4081 uint32_t BitWidth = AndRHSMask.getBitWidth();
4082 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4083 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4084
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004085 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004086 if (!(A && A->isZero()) && // avoid infinite recursion.
4087 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004088 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004089 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4090 }
4091 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004092 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004093
4094 case Instruction::Shl:
4095 case Instruction::LShr:
4096 // (1 << x) & 1 --> zext(x == 0)
4097 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004098 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004099 Value *NewICmp =
4100 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004101 return new ZExtInst(NewICmp, I.getType());
4102 }
4103 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004104 }
4105
Chris Lattner58403262003-07-23 19:25:52 +00004106 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004107 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004108 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004109 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004110 // If this is an integer truncation or change from signed-to-unsigned, and
4111 // if the source is an and/or with immediate, transform it. This
4112 // frequently occurs for bitfield accesses.
4113 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004114 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004115 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004116 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004117 if (CastOp->getOpcode() == Instruction::And) {
4118 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004119 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4120 // This will fold the two constants together, which may allow
4121 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004122 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004123 CastOp->getOperand(0), I.getType(),
4124 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004125 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004126 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004127 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004128 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004129 } else if (CastOp->getOpcode() == Instruction::Or) {
4130 // Change: and (cast (or X, C1) to T), C2
4131 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004132 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004133 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004134 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004135 return ReplaceInstUsesWith(I, AndRHS);
4136 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004137 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004138 }
Chris Lattner06782f82003-07-23 19:36:21 +00004139 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004140
4141 // Try to fold constant and into select arguments.
4142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004144 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004145 if (isa<PHINode>(Op0))
4146 if (Instruction *NV = FoldOpIntoPhi(I))
4147 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004148 }
4149
Dan Gohman186a6362009-08-12 16:04:34 +00004150 Value *Op0NotVal = dyn_castNotVal(Op0);
4151 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004152
Chris Lattner5b62aa72004-06-18 06:07:51 +00004153 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004154 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004155
Misha Brukmancb6267b2004-07-30 12:50:08 +00004156 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004157 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004158 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4159 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004160 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004161 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004162
4163 {
Chris Lattner003b6202007-06-15 05:58:24 +00004164 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004165 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004166 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4167 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004168
4169 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004170 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004171 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004172 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004173 }
4174 }
4175
Dan Gohman4ae51262009-08-12 16:23:25 +00004176 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004177 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4178 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004179
4180 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004181 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004182 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004183 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004184 }
4185 }
Chris Lattner64daab52006-04-01 08:03:55 +00004186
4187 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004188 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004189 if (A == Op1) { // (A^B)&A -> A&(A^B)
4190 I.swapOperands(); // Simplify below
4191 std::swap(Op0, Op1);
4192 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4193 cast<BinaryOperator>(Op0)->swapOperands();
4194 I.swapOperands(); // Simplify below
4195 std::swap(Op0, Op1);
4196 }
4197 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004198
Chris Lattner64daab52006-04-01 08:03:55 +00004199 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004200 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004201 if (B == Op0) { // B&(A^B) -> B&(B^A)
4202 cast<BinaryOperator>(Op1)->swapOperands();
4203 std::swap(A, B);
4204 }
Chris Lattner74381062009-08-30 07:44:24 +00004205 if (A == Op0) // A&(A^B) -> A & ~B
4206 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004207 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004208
4209 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004210 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4211 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004212 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004213 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4214 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004215 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004216 }
4217
Reid Spencere4d87aa2006-12-23 06:05:41 +00004218 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4219 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004220 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004221 return R;
4222
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004223 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4224 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4225 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004226 }
4227
Chris Lattner6fc205f2006-05-05 06:39:07 +00004228 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004229 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4230 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4231 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4232 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004233 if (SrcTy == Op1C->getOperand(0)->getType() &&
4234 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004235 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004236 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4237 I.getType(), TD) &&
4238 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4239 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004240 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4241 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004242 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004243 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004244 }
Chris Lattnere511b742006-11-14 07:46:50 +00004245
4246 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004247 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4248 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4249 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004250 SI0->getOperand(1) == SI1->getOperand(1) &&
4251 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004252 Value *NewOp =
4253 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4254 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004255 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004256 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004257 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004258 }
4259
Evan Cheng8db90722008-10-14 17:15:11 +00004260 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004261 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004262 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4263 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4264 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004265 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004266
Chris Lattner7e708292002-06-25 16:13:24 +00004267 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004268}
4269
Chris Lattner8c34cd22008-10-05 02:13:19 +00004270/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4271/// capable of providing pieces of a bswap. The subexpression provides pieces
4272/// of a bswap if it is proven that each of the non-zero bytes in the output of
4273/// the expression came from the corresponding "byte swapped" byte in some other
4274/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4275/// we know that the expression deposits the low byte of %X into the high byte
4276/// of the bswap result and that all other bytes are zero. This expression is
4277/// accepted, the high byte of ByteValues is set to X to indicate a correct
4278/// match.
4279///
4280/// This function returns true if the match was unsuccessful and false if so.
4281/// On entry to the function the "OverallLeftShift" is a signed integer value
4282/// indicating the number of bytes that the subexpression is later shifted. For
4283/// example, if the expression is later right shifted by 16 bits, the
4284/// OverallLeftShift value would be -2 on entry. This is used to specify which
4285/// byte of ByteValues is actually being set.
4286///
4287/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4288/// byte is masked to zero by a user. For example, in (X & 255), X will be
4289/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4290/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4291/// always in the local (OverallLeftShift) coordinate space.
4292///
4293static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4294 SmallVector<Value*, 8> &ByteValues) {
4295 if (Instruction *I = dyn_cast<Instruction>(V)) {
4296 // If this is an or instruction, it may be an inner node of the bswap.
4297 if (I->getOpcode() == Instruction::Or) {
4298 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4299 ByteValues) ||
4300 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4301 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004302 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004303
4304 // If this is a logical shift by a constant multiple of 8, recurse with
4305 // OverallLeftShift and ByteMask adjusted.
4306 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4307 unsigned ShAmt =
4308 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4309 // Ensure the shift amount is defined and of a byte value.
4310 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4311 return true;
4312
4313 unsigned ByteShift = ShAmt >> 3;
4314 if (I->getOpcode() == Instruction::Shl) {
4315 // X << 2 -> collect(X, +2)
4316 OverallLeftShift += ByteShift;
4317 ByteMask >>= ByteShift;
4318 } else {
4319 // X >>u 2 -> collect(X, -2)
4320 OverallLeftShift -= ByteShift;
4321 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004322 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004323 }
4324
4325 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4326 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4327
4328 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4329 ByteValues);
4330 }
4331
4332 // If this is a logical 'and' with a mask that clears bytes, clear the
4333 // corresponding bytes in ByteMask.
4334 if (I->getOpcode() == Instruction::And &&
4335 isa<ConstantInt>(I->getOperand(1))) {
4336 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4337 unsigned NumBytes = ByteValues.size();
4338 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4339 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4340
4341 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4342 // If this byte is masked out by a later operation, we don't care what
4343 // the and mask is.
4344 if ((ByteMask & (1 << i)) == 0)
4345 continue;
4346
4347 // If the AndMask is all zeros for this byte, clear the bit.
4348 APInt MaskB = AndMask & Byte;
4349 if (MaskB == 0) {
4350 ByteMask &= ~(1U << i);
4351 continue;
4352 }
4353
4354 // If the AndMask is not all ones for this byte, it's not a bytezap.
4355 if (MaskB != Byte)
4356 return true;
4357
4358 // Otherwise, this byte is kept.
4359 }
4360
4361 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4362 ByteValues);
4363 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004364 }
4365
Chris Lattner8c34cd22008-10-05 02:13:19 +00004366 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4367 // the input value to the bswap. Some observations: 1) if more than one byte
4368 // is demanded from this input, then it could not be successfully assembled
4369 // into a byteswap. At least one of the two bytes would not be aligned with
4370 // their ultimate destination.
4371 if (!isPowerOf2_32(ByteMask)) return true;
4372 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004373
Chris Lattner8c34cd22008-10-05 02:13:19 +00004374 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4375 // is demanded, it needs to go into byte 0 of the result. This means that the
4376 // byte needs to be shifted until it lands in the right byte bucket. The
4377 // shift amount depends on the position: if the byte is coming from the high
4378 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4379 // low part, it must be shifted left.
4380 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4381 if (InputByteNo < ByteValues.size()/2) {
4382 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4383 return true;
4384 } else {
4385 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4386 return true;
4387 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004388
4389 // If the destination byte value is already defined, the values are or'd
4390 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004391 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004392 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004393 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004394 return false;
4395}
4396
4397/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4398/// If so, insert the new bswap intrinsic and return it.
4399Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004400 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004401 if (!ITy || ITy->getBitWidth() % 16 ||
4402 // ByteMask only allows up to 32-byte values.
4403 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004404 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004405
4406 /// ByteValues - For each byte of the result, we keep track of which value
4407 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004408 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004409 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004410
4411 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004412 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4413 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004414 return 0;
4415
4416 // Check to see if all of the bytes come from the same value.
4417 Value *V = ByteValues[0];
4418 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4419
4420 // Check to make sure that all of the bytes come from the same value.
4421 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4422 if (ByteValues[i] != V)
4423 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004424 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004425 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004426 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004427 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004428}
4429
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004430/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4431/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4432/// we can simplify this expression to "cond ? C : D or B".
4433static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004434 Value *C, Value *D,
4435 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004436 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004437 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004438 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004439 return 0;
4440
Chris Lattnera6a474d2008-11-16 04:26:55 +00004441 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004442 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004443 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004444 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004445 return SelectInst::Create(Cond, C, B);
4446 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004447 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004448 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004449 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004450 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004451 return 0;
4452}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004453
Chris Lattner69d4ced2008-11-16 05:20:07 +00004454/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4455Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4456 ICmpInst *LHS, ICmpInst *RHS) {
4457 Value *Val, *Val2;
4458 ConstantInt *LHSCst, *RHSCst;
4459 ICmpInst::Predicate LHSCC, RHSCC;
4460
4461 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004462 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004463 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004464 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004465 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004466 return 0;
4467
4468 // From here on, we only handle:
4469 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4470 if (Val != Val2) return 0;
4471
4472 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4473 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4474 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4475 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4476 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4477 return 0;
4478
4479 // We can't fold (ugt x, C) | (sgt x, C2).
4480 if (!PredicatesFoldable(LHSCC, RHSCC))
4481 return 0;
4482
4483 // Ensure that the larger constant is on the RHS.
4484 bool ShouldSwap;
4485 if (ICmpInst::isSignedPredicate(LHSCC) ||
4486 (ICmpInst::isEquality(LHSCC) &&
4487 ICmpInst::isSignedPredicate(RHSCC)))
4488 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4489 else
4490 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4491
4492 if (ShouldSwap) {
4493 std::swap(LHS, RHS);
4494 std::swap(LHSCst, RHSCst);
4495 std::swap(LHSCC, RHSCC);
4496 }
4497
4498 // At this point, we know we have have two icmp instructions
4499 // comparing a value against two constants and or'ing the result
4500 // together. Because of the above check, we know that we only have
4501 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4502 // FoldICmpLogical check above), that the two constants are not
4503 // equal.
4504 assert(LHSCst != RHSCst && "Compares not folded above?");
4505
4506 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004507 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004508 case ICmpInst::ICMP_EQ:
4509 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004510 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004511 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004512 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004513 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004514 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004515 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004516 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004517 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004518 }
4519 break; // (X == 13 | X == 15) -> no change
4520 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4521 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4522 break;
4523 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4524 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4525 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4526 return ReplaceInstUsesWith(I, RHS);
4527 }
4528 break;
4529 case ICmpInst::ICMP_NE:
4530 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004531 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004532 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4533 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4534 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4535 return ReplaceInstUsesWith(I, LHS);
4536 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4537 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4538 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004539 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004540 }
4541 break;
4542 case ICmpInst::ICMP_ULT:
4543 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004544 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004545 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4546 break;
4547 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4548 // If RHSCst is [us]MAXINT, it is always false. Not handling
4549 // this can cause overflow.
4550 if (RHSCst->isMaxValue(false))
4551 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004552 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004553 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004554 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4555 break;
4556 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4557 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4558 return ReplaceInstUsesWith(I, RHS);
4559 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4560 break;
4561 }
4562 break;
4563 case ICmpInst::ICMP_SLT:
4564 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004565 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004566 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4567 break;
4568 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4569 // If RHSCst is [us]MAXINT, it is always false. Not handling
4570 // this can cause overflow.
4571 if (RHSCst->isMaxValue(true))
4572 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004573 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004574 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004575 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4576 break;
4577 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4578 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4579 return ReplaceInstUsesWith(I, RHS);
4580 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4581 break;
4582 }
4583 break;
4584 case ICmpInst::ICMP_UGT:
4585 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004586 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004587 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4588 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4589 return ReplaceInstUsesWith(I, LHS);
4590 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4591 break;
4592 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4593 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004594 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004595 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4596 break;
4597 }
4598 break;
4599 case ICmpInst::ICMP_SGT:
4600 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004601 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004602 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4603 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4604 return ReplaceInstUsesWith(I, LHS);
4605 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4606 break;
4607 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4608 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004609 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004610 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4611 break;
4612 }
4613 break;
4614 }
4615 return 0;
4616}
4617
Chris Lattner5414cc52009-07-23 05:46:22 +00004618Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4619 FCmpInst *RHS) {
4620 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4621 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4622 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4623 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4624 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4625 // If either of the constants are nans, then the whole thing returns
4626 // true.
4627 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004628 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004629
4630 // Otherwise, no need to compare the two constants, compare the
4631 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004632 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004633 LHS->getOperand(0), RHS->getOperand(0));
4634 }
4635
4636 // Handle vector zeros. This occurs because the canonical form of
4637 // "fcmp uno x,x" is "fcmp uno x, 0".
4638 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4639 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004640 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004641 LHS->getOperand(0), RHS->getOperand(0));
4642
4643 return 0;
4644 }
4645
4646 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4647 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4648 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4649
4650 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4651 // Swap RHS operands to match LHS.
4652 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4653 std::swap(Op1LHS, Op1RHS);
4654 }
4655 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4656 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4657 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004658 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004659 Op0LHS, Op0RHS);
4660 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004661 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004662 if (Op0CC == FCmpInst::FCMP_FALSE)
4663 return ReplaceInstUsesWith(I, RHS);
4664 if (Op1CC == FCmpInst::FCMP_FALSE)
4665 return ReplaceInstUsesWith(I, LHS);
4666 bool Op0Ordered;
4667 bool Op1Ordered;
4668 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4669 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4670 if (Op0Ordered == Op1Ordered) {
4671 // If both are ordered or unordered, return a new fcmp with
4672 // or'ed predicates.
4673 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4674 Op0LHS, Op0RHS, Context);
4675 if (Instruction *I = dyn_cast<Instruction>(RV))
4676 return I;
4677 // Otherwise, it's a constant boolean value...
4678 return ReplaceInstUsesWith(I, RV);
4679 }
4680 }
4681 return 0;
4682}
4683
Bill Wendlinga698a472008-12-01 08:23:25 +00004684/// FoldOrWithConstants - This helper function folds:
4685///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004686/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004687///
4688/// into:
4689///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004690/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004691///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004692/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004693Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004694 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004695 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4696 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004697
Bill Wendling286a0542008-12-02 06:24:20 +00004698 Value *V1 = 0;
4699 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004700 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004701
Bill Wendling29976b92008-12-02 06:18:11 +00004702 APInt Xor = CI1->getValue() ^ CI2->getValue();
4703 if (!Xor.isAllOnesValue()) return 0;
4704
Bill Wendling286a0542008-12-02 06:24:20 +00004705 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004706 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004707 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004708 }
4709
4710 return 0;
4711}
4712
Chris Lattner7e708292002-06-25 16:13:24 +00004713Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004714 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004716
Chris Lattner42593e62007-03-24 23:56:43 +00004717 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004718 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004719
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004720 // or X, X = X
4721 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004722 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004723
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004724 // See if we can simplify any instructions used by the instruction whose sole
4725 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004726 if (SimplifyDemandedInstructionBits(I))
4727 return &I;
4728 if (isa<VectorType>(I.getType())) {
4729 if (isa<ConstantAggregateZero>(Op1)) {
4730 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4731 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4732 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4733 return ReplaceInstUsesWith(I, I.getOperand(1));
4734 }
Chris Lattner42593e62007-03-24 23:56:43 +00004735 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004736
Chris Lattner3f5b8772002-05-06 16:14:14 +00004737 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004738 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004739 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004740 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004741 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004742 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004743 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004744 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004745 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004746 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004747 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004748
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004749 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004750 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004751 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004752 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004753 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004754 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004755 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004756 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004757
4758 // Try to fold constant and into select arguments.
4759 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004760 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004761 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004762 if (isa<PHINode>(Op0))
4763 if (Instruction *NV = FoldOpIntoPhi(I))
4764 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004765 }
4766
Chris Lattner4f637d42006-01-06 17:59:59 +00004767 Value *A = 0, *B = 0;
4768 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004769
Dan Gohman4ae51262009-08-12 16:23:25 +00004770 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004771 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4772 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004773 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004774 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4775 return ReplaceInstUsesWith(I, Op0);
4776
Chris Lattner6423d4c2006-07-10 20:25:24 +00004777 // (A | B) | C and A | (B | C) -> bswap if possible.
4778 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004779 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4780 match(Op1, m_Or(m_Value(), m_Value())) ||
4781 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4782 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004783 if (Instruction *BSwap = MatchBSwap(I))
4784 return BSwap;
4785 }
4786
Chris Lattner6e4c6492005-05-09 04:58:36 +00004787 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004788 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004789 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004790 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004791 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004792 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004793 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004794 }
4795
4796 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004797 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004798 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004799 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004800 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004801 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004802 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004803 }
4804
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004805 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004806 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004807 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4808 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004809 Value *V1 = 0, *V2 = 0, *V3 = 0;
4810 C1 = dyn_cast<ConstantInt>(C);
4811 C2 = dyn_cast<ConstantInt>(D);
4812 if (C1 && C2) { // (A & C1)|(B & C2)
4813 // If we have: ((V + N) & C1) | (V & C2)
4814 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4815 // replace with V+N.
4816 if (C1->getValue() == ~C2->getValue()) {
4817 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004818 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004819 // Add commutes, try both ways.
4820 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4821 return ReplaceInstUsesWith(I, A);
4822 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4823 return ReplaceInstUsesWith(I, A);
4824 }
4825 // Or commutes, try both ways.
4826 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004827 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004828 // Add commutes, try both ways.
4829 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4830 return ReplaceInstUsesWith(I, B);
4831 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4832 return ReplaceInstUsesWith(I, B);
4833 }
4834 }
Chris Lattner044e5332007-04-08 08:01:49 +00004835 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004836 }
4837
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004838 // Check to see if we have any common things being and'ed. If so, find the
4839 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004840 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4841 if (A == B) // (A & C)|(A & D) == A & (C|D)
4842 V1 = A, V2 = C, V3 = D;
4843 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4844 V1 = A, V2 = B, V3 = C;
4845 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4846 V1 = C, V2 = A, V3 = D;
4847 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4848 V1 = C, V2 = A, V3 = B;
4849
4850 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004851 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004852 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004853 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004854 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004855
Dan Gohman1975d032008-10-30 20:40:10 +00004856 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004857 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004858 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004859 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004860 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004861 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004862 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004863 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004864 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004865
Bill Wendlingb01865c2008-11-30 13:52:49 +00004866 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004867 if ((match(C, m_Not(m_Specific(D))) &&
4868 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004869 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004870 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004871 if ((match(A, m_Not(m_Specific(D))) &&
4872 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004873 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004874 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004875 if ((match(C, m_Not(m_Specific(B))) &&
4876 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004877 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004878 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004879 if ((match(A, m_Not(m_Specific(B))) &&
4880 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004881 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004882 }
Chris Lattnere511b742006-11-14 07:46:50 +00004883
4884 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004885 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4886 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4887 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004888 SI0->getOperand(1) == SI1->getOperand(1) &&
4889 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004890 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4891 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004892 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004893 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004894 }
4895 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004896
Bill Wendlingb3833d12008-12-01 01:07:11 +00004897 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004898 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4899 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004900 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004901 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004902 }
4903 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004904 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4905 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004906 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004907 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004908 }
4909
Dan Gohman4ae51262009-08-12 16:23:25 +00004910 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004911 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004912 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004913 } else {
4914 A = 0;
4915 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004916 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004917 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004918 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004919 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004920
Misha Brukmancb6267b2004-07-30 12:50:08 +00004921 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004922 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004923 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004924 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004925 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004926 }
Chris Lattnera2881962003-02-18 19:28:33 +00004927
Reid Spencere4d87aa2006-12-23 06:05:41 +00004928 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4929 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004930 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004931 return R;
4932
Chris Lattner69d4ced2008-11-16 05:20:07 +00004933 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4934 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4935 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004936 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004937
4938 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004939 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004940 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004941 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004942 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4943 !isa<ICmpInst>(Op1C->getOperand(0))) {
4944 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004945 if (SrcTy == Op1C->getOperand(0)->getType() &&
4946 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004947 // Only do this if the casts both really cause code to be
4948 // generated.
4949 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4950 I.getType(), TD) &&
4951 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4952 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004953 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4954 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004955 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004956 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004957 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004958 }
Chris Lattner99c65742007-10-24 05:38:08 +00004959 }
4960
4961
4962 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4963 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004964 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4965 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4966 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004967 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004968
Chris Lattner7e708292002-06-25 16:13:24 +00004969 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004970}
4971
Dan Gohman844731a2008-05-13 00:00:25 +00004972namespace {
4973
Chris Lattnerc317d392004-02-16 01:20:27 +00004974// XorSelf - Implements: X ^ X --> 0
4975struct XorSelf {
4976 Value *RHS;
4977 XorSelf(Value *rhs) : RHS(rhs) {}
4978 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4979 Instruction *apply(BinaryOperator &Xor) const {
4980 return &Xor;
4981 }
4982};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004983
Dan Gohman844731a2008-05-13 00:00:25 +00004984}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004985
Chris Lattner7e708292002-06-25 16:13:24 +00004986Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004987 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004988 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004989
Evan Chengd34af782008-03-25 20:07:13 +00004990 if (isa<UndefValue>(Op1)) {
4991 if (isa<UndefValue>(Op0))
4992 // Handle undef ^ undef -> 0 special case. This is a common
4993 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004995 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004996 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004997
Chris Lattnerc317d392004-02-16 01:20:27 +00004998 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00004999 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005000 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005001 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005002 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005003
5004 // See if we can simplify any instructions used by the instruction whose sole
5005 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005006 if (SimplifyDemandedInstructionBits(I))
5007 return &I;
5008 if (isa<VectorType>(I.getType()))
5009 if (isa<ConstantAggregateZero>(Op1))
5010 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005011
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005012 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005013 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005014 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5015 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5016 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5017 if (Op0I->getOpcode() == Instruction::And ||
5018 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005019 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5020 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005021 Value *NotY =
5022 Builder->CreateNot(Op0I->getOperand(1),
5023 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005024 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005025 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005026 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005027 }
5028 }
5029 }
5030 }
5031
5032
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005033 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005034 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005035 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005036 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005037 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005038 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005039
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005040 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005041 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005042 FCI->getOperand(0), FCI->getOperand(1));
5043 }
5044
Nick Lewycky517e1f52008-05-31 19:01:33 +00005045 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5046 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5047 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5048 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5049 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005050 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5051 (RHS == ConstantExpr::getCast(Opcode,
5052 ConstantInt::getTrue(*Context),
5053 Op0C->getDestTy()))) {
5054 CI->setPredicate(CI->getInversePredicate());
5055 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005056 }
5057 }
5058 }
5059 }
5060
Reid Spencere4d87aa2006-12-23 06:05:41 +00005061 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005062 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005063 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5064 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005065 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5066 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005067 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005068 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005069 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005070
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005071 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005072 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005073 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005074 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005075 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005076 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005077 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005078 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005079 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005080 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005081 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005082 Constant *C = ConstantInt::get(*Context,
5083 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005084 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005085
Chris Lattner7c4049c2004-01-12 19:35:11 +00005086 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005087 } else if (Op0I->getOpcode() == Instruction::Or) {
5088 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005089 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005090 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005091 // Anything in both C1 and C2 is known to be zero, remove it from
5092 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005093 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5094 NewRHS = ConstantExpr::getAnd(NewRHS,
5095 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005096 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005097 I.setOperand(0, Op0I->getOperand(0));
5098 I.setOperand(1, NewRHS);
5099 return &I;
5100 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005101 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005102 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005103 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005104
5105 // Try to fold constant and into select arguments.
5106 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005107 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005108 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005109 if (isa<PHINode>(Op0))
5110 if (Instruction *NV = FoldOpIntoPhi(I))
5111 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005112 }
5113
Dan Gohman186a6362009-08-12 16:04:34 +00005114 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005115 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005116 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005117
Dan Gohman186a6362009-08-12 16:04:34 +00005118 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005119 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005120 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005121
Chris Lattner318bf792007-03-18 22:51:34 +00005122
5123 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5124 if (Op1I) {
5125 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005126 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005127 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005128 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005129 I.swapOperands();
5130 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005131 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005132 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005133 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005134 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005135 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005136 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005137 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005138 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005139 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005140 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005141 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005142 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005143 std::swap(A, B);
5144 }
Chris Lattner318bf792007-03-18 22:51:34 +00005145 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005146 I.swapOperands(); // Simplified below.
5147 std::swap(Op0, Op1);
5148 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005149 }
Chris Lattner318bf792007-03-18 22:51:34 +00005150 }
5151
5152 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5153 if (Op0I) {
5154 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005155 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005156 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005157 if (A == Op1) // (B|A)^B == (A|B)^B
5158 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005159 if (B == Op1) // (A|B)^B == A & ~B
5160 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005161 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005162 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005163 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005164 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005165 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005166 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005167 if (A == Op1) // (A&B)^A -> (B&A)^A
5168 std::swap(A, B);
5169 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005170 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005171 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005172 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005173 }
Chris Lattner318bf792007-03-18 22:51:34 +00005174 }
5175
5176 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5177 if (Op0I && Op1I && Op0I->isShift() &&
5178 Op0I->getOpcode() == Op1I->getOpcode() &&
5179 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5180 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005181 Value *NewOp =
5182 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5183 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005184 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005185 Op1I->getOperand(1));
5186 }
5187
5188 if (Op0I && Op1I) {
5189 Value *A, *B, *C, *D;
5190 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005191 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5192 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005193 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005194 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005195 }
5196 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005197 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5198 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005199 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005200 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005201 }
5202
5203 // (A & B)^(C & D)
5204 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005205 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5206 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005207 // (X & Y)^(X & Y) -> (Y^Z) & X
5208 Value *X = 0, *Y = 0, *Z = 0;
5209 if (A == C)
5210 X = A, Y = B, Z = D;
5211 else if (A == D)
5212 X = A, Y = B, Z = C;
5213 else if (B == C)
5214 X = B, Y = A, Z = D;
5215 else if (B == D)
5216 X = B, Y = A, Z = C;
5217
5218 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005219 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005220 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005221 }
5222 }
5223 }
5224
Reid Spencere4d87aa2006-12-23 06:05:41 +00005225 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5226 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005227 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005228 return R;
5229
Chris Lattner6fc205f2006-05-05 06:39:07 +00005230 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005231 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005232 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005233 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5234 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005235 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005236 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005237 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5238 I.getType(), TD) &&
5239 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5240 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005241 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5242 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005243 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005244 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005245 }
Chris Lattner99c65742007-10-24 05:38:08 +00005246 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005247
Chris Lattner7e708292002-06-25 16:13:24 +00005248 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005249}
5250
Owen Andersond672ecb2009-07-03 00:17:18 +00005251static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005252 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005253 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005254}
Chris Lattnera96879a2004-09-29 17:40:11 +00005255
Dan Gohman6de29f82009-06-15 22:12:54 +00005256static bool HasAddOverflow(ConstantInt *Result,
5257 ConstantInt *In1, ConstantInt *In2,
5258 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005259 if (IsSigned)
5260 if (In2->getValue().isNegative())
5261 return Result->getValue().sgt(In1->getValue());
5262 else
5263 return Result->getValue().slt(In1->getValue());
5264 else
5265 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005266}
5267
Dan Gohman6de29f82009-06-15 22:12:54 +00005268/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005269/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005270static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005271 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005272 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005273 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005274
Dan Gohman6de29f82009-06-15 22:12:54 +00005275 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5276 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005277 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005278 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5279 ExtractElement(In1, Idx, Context),
5280 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005281 IsSigned))
5282 return true;
5283 }
5284 return false;
5285 }
5286
5287 return HasAddOverflow(cast<ConstantInt>(Result),
5288 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5289 IsSigned);
5290}
5291
5292static bool HasSubOverflow(ConstantInt *Result,
5293 ConstantInt *In1, ConstantInt *In2,
5294 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005295 if (IsSigned)
5296 if (In2->getValue().isNegative())
5297 return Result->getValue().slt(In1->getValue());
5298 else
5299 return Result->getValue().sgt(In1->getValue());
5300 else
5301 return Result->getValue().ugt(In1->getValue());
5302}
5303
Dan Gohman6de29f82009-06-15 22:12:54 +00005304/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5305/// overflowed for this type.
5306static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005307 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005308 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005309 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005310
5311 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5312 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005313 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005314 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5315 ExtractElement(In1, Idx, Context),
5316 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005317 IsSigned))
5318 return true;
5319 }
5320 return false;
5321 }
5322
5323 return HasSubOverflow(cast<ConstantInt>(Result),
5324 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5325 IsSigned);
5326}
5327
Chris Lattner574da9b2005-01-13 20:14:25 +00005328/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5329/// code necessary to compute the offset from the base pointer (without adding
5330/// in the base pointer). Return the result as a signed integer of intptr size.
5331static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005332 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005333 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005334 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005335 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005336
5337 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005338 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005339 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005340
Gabor Greif177dd3f2008-06-12 21:37:33 +00005341 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5342 ++i, ++GTI) {
5343 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005344 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005345 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5346 if (OpC->isZero()) continue;
5347
5348 // Handle a struct index, which adds its field offset to the pointer.
5349 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5350 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5351
Chris Lattner74381062009-08-30 07:44:24 +00005352 Result = IC.Builder->CreateAdd(Result,
5353 ConstantInt::get(IntPtrTy, Size),
5354 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005355 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005356 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005357
Owen Andersoneed707b2009-07-24 23:12:02 +00005358 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005359 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005360 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5361 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005362 // Emit an add instruction.
5363 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005364 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005365 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005366 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005367 if (Op->getType() != IntPtrTy)
5368 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005369 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005370 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005371 // We'll let instcombine(mul) convert this to a shl if possible.
5372 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005373 }
5374
5375 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005376 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005377 }
5378 return Result;
5379}
5380
Chris Lattner10c0d912008-04-22 02:53:33 +00005381
Dan Gohman8f080f02009-07-17 22:16:21 +00005382/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5383/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5384/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5385/// be complex, and scales are involved. The above expression would also be
5386/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5387/// This later form is less amenable to optimization though, and we are allowed
5388/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005389///
5390/// If we can't emit an optimized form for this expression, this returns null.
5391///
5392static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5393 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005394 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005395 gep_type_iterator GTI = gep_type_begin(GEP);
5396
5397 // Check to see if this gep only has a single variable index. If so, and if
5398 // any constant indices are a multiple of its scale, then we can compute this
5399 // in terms of the scale of the variable index. For example, if the GEP
5400 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5401 // because the expression will cross zero at the same point.
5402 unsigned i, e = GEP->getNumOperands();
5403 int64_t Offset = 0;
5404 for (i = 1; i != e; ++i, ++GTI) {
5405 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5406 // Compute the aggregate offset of constant indices.
5407 if (CI->isZero()) continue;
5408
5409 // Handle a struct index, which adds its field offset to the pointer.
5410 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5411 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5412 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005413 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005414 Offset += Size*CI->getSExtValue();
5415 }
5416 } else {
5417 // Found our variable index.
5418 break;
5419 }
5420 }
5421
5422 // If there are no variable indices, we must have a constant offset, just
5423 // evaluate it the general way.
5424 if (i == e) return 0;
5425
5426 Value *VariableIdx = GEP->getOperand(i);
5427 // Determine the scale factor of the variable element. For example, this is
5428 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005429 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005430
5431 // Verify that there are no other variable indices. If so, emit the hard way.
5432 for (++i, ++GTI; i != e; ++i, ++GTI) {
5433 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5434 if (!CI) return 0;
5435
5436 // Compute the aggregate offset of constant indices.
5437 if (CI->isZero()) continue;
5438
5439 // Handle a struct index, which adds its field offset to the pointer.
5440 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5441 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5442 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005443 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005444 Offset += Size*CI->getSExtValue();
5445 }
5446 }
5447
5448 // Okay, we know we have a single variable index, which must be a
5449 // pointer/array/vector index. If there is no offset, life is simple, return
5450 // the index.
5451 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5452 if (Offset == 0) {
5453 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5454 // we don't need to bother extending: the extension won't affect where the
5455 // computation crosses zero.
5456 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005457 VariableIdx = new TruncInst(VariableIdx,
5458 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005459 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005460 return VariableIdx;
5461 }
5462
5463 // Otherwise, there is an index. The computation we will do will be modulo
5464 // the pointer size, so get it.
5465 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5466
5467 Offset &= PtrSizeMask;
5468 VariableScale &= PtrSizeMask;
5469
5470 // To do this transformation, any constant index must be a multiple of the
5471 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5472 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5473 // multiple of the variable scale.
5474 int64_t NewOffs = Offset / (int64_t)VariableScale;
5475 if (Offset != NewOffs*(int64_t)VariableScale)
5476 return 0;
5477
5478 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005479 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005480 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005481 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005482 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005483 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005484 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005485 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005486}
5487
5488
Reid Spencere4d87aa2006-12-23 06:05:41 +00005489/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005490/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005491Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005492 ICmpInst::Predicate Cond,
5493 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005494 // Look through bitcasts.
5495 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5496 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005497
Chris Lattner574da9b2005-01-13 20:14:25 +00005498 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005499 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005500 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005501 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005502 // know pointers can't overflow since the gep is inbounds. See if we can
5503 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005504 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5505
5506 // If not, synthesize the offset the hard way.
5507 if (Offset == 0)
5508 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005509 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005510 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005511 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005512 // If the base pointers are different, but the indices are the same, just
5513 // compare the base pointer.
5514 if (PtrBase != GEPRHS->getOperand(0)) {
5515 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005516 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005517 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005518 if (IndicesTheSame)
5519 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5520 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5521 IndicesTheSame = false;
5522 break;
5523 }
5524
5525 // If all indices are the same, just compare the base pointers.
5526 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005527 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005528 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005529
5530 // Otherwise, the base pointers are different and the indices are
5531 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005532 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005533 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005534
Chris Lattnere9d782b2005-01-13 22:25:21 +00005535 // If one of the GEPs has all zero indices, recurse.
5536 bool AllZeros = true;
5537 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5538 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5539 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5540 AllZeros = false;
5541 break;
5542 }
5543 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005544 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5545 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005546
5547 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005548 AllZeros = true;
5549 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5550 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5551 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5552 AllZeros = false;
5553 break;
5554 }
5555 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005556 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005557
Chris Lattner4401c9c2005-01-14 00:20:05 +00005558 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5559 // If the GEPs only differ by one index, compare it.
5560 unsigned NumDifferences = 0; // Keep track of # differences.
5561 unsigned DiffOperand = 0; // The operand that differs.
5562 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5563 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005564 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5565 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005566 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005567 NumDifferences = 2;
5568 break;
5569 } else {
5570 if (NumDifferences++) break;
5571 DiffOperand = i;
5572 }
5573 }
5574
5575 if (NumDifferences == 0) // SAME GEP?
5576 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005577 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005578 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005579
Chris Lattner4401c9c2005-01-14 00:20:05 +00005580 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005581 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5582 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005583 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005584 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005585 }
5586 }
5587
Reid Spencere4d87aa2006-12-23 06:05:41 +00005588 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005589 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005590 if (TD &&
5591 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005592 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5593 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5594 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5595 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005596 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005597 }
5598 }
5599 return 0;
5600}
5601
Chris Lattnera5406232008-05-19 20:18:56 +00005602/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5603///
5604Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5605 Instruction *LHSI,
5606 Constant *RHSC) {
5607 if (!isa<ConstantFP>(RHSC)) return 0;
5608 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5609
5610 // Get the width of the mantissa. We don't want to hack on conversions that
5611 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005612 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005613 if (MantissaWidth == -1) return 0; // Unknown.
5614
5615 // Check to see that the input is converted from an integer type that is small
5616 // enough that preserves all bits. TODO: check here for "known" sign bits.
5617 // 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 +00005618 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005619
5620 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005621 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5622 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005623 ++InputSize;
5624
5625 // If the conversion would lose info, don't hack on this.
5626 if ((int)InputSize > MantissaWidth)
5627 return 0;
5628
5629 // Otherwise, we can potentially simplify the comparison. We know that it
5630 // will always come through as an integer value and we know the constant is
5631 // not a NAN (it would have been previously simplified).
5632 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5633
5634 ICmpInst::Predicate Pred;
5635 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005636 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005637 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005638 case FCmpInst::FCMP_OEQ:
5639 Pred = ICmpInst::ICMP_EQ;
5640 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005641 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005642 case FCmpInst::FCMP_OGT:
5643 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5644 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005645 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005646 case FCmpInst::FCMP_OGE:
5647 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5648 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005649 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005650 case FCmpInst::FCMP_OLT:
5651 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5652 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005653 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005654 case FCmpInst::FCMP_OLE:
5655 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5656 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005657 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005658 case FCmpInst::FCMP_ONE:
5659 Pred = ICmpInst::ICMP_NE;
5660 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005661 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005663 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005664 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005665 }
5666
5667 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5668
5669 // Now we know that the APFloat is a normal number, zero or inf.
5670
Chris Lattner85162782008-05-20 03:50:52 +00005671 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005672 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005673 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005674
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005675 if (!LHSUnsigned) {
5676 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5677 // and large values.
5678 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5679 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5680 APFloat::rmNearestTiesToEven);
5681 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5682 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5683 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005684 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5685 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005686 }
5687 } else {
5688 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5689 // +INF and large values.
5690 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5691 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5692 APFloat::rmNearestTiesToEven);
5693 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5694 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5695 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005696 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5697 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005698 }
Chris Lattnera5406232008-05-19 20:18:56 +00005699 }
5700
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005701 if (!LHSUnsigned) {
5702 // See if the RHS value is < SignedMin.
5703 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5704 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5705 APFloat::rmNearestTiesToEven);
5706 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5707 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5708 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005709 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5710 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005711 }
Chris Lattnera5406232008-05-19 20:18:56 +00005712 }
5713
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005714 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5715 // [0, UMAX], but it may still be fractional. See if it is fractional by
5716 // casting the FP value to the integer value and back, checking for equality.
5717 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005718 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005719 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5720 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005721 if (!RHS.isZero()) {
5722 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005723 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5724 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005725 if (!Equal) {
5726 // If we had a comparison against a fractional value, we have to adjust
5727 // the compare predicate and sometimes the value. RHSC is rounded towards
5728 // zero at this point.
5729 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005730 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005731 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005732 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005733 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005734 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005735 case ICmpInst::ICMP_ULE:
5736 // (float)int <= 4.4 --> int <= 4
5737 // (float)int <= -4.4 --> false
5738 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005739 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005740 break;
5741 case ICmpInst::ICMP_SLE:
5742 // (float)int <= 4.4 --> int <= 4
5743 // (float)int <= -4.4 --> int < -4
5744 if (RHS.isNegative())
5745 Pred = ICmpInst::ICMP_SLT;
5746 break;
5747 case ICmpInst::ICMP_ULT:
5748 // (float)int < -4.4 --> false
5749 // (float)int < 4.4 --> int <= 4
5750 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005751 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005752 Pred = ICmpInst::ICMP_ULE;
5753 break;
5754 case ICmpInst::ICMP_SLT:
5755 // (float)int < -4.4 --> int < -4
5756 // (float)int < 4.4 --> int <= 4
5757 if (!RHS.isNegative())
5758 Pred = ICmpInst::ICMP_SLE;
5759 break;
5760 case ICmpInst::ICMP_UGT:
5761 // (float)int > 4.4 --> int > 4
5762 // (float)int > -4.4 --> true
5763 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005764 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005765 break;
5766 case ICmpInst::ICMP_SGT:
5767 // (float)int > 4.4 --> int > 4
5768 // (float)int > -4.4 --> int >= -4
5769 if (RHS.isNegative())
5770 Pred = ICmpInst::ICMP_SGE;
5771 break;
5772 case ICmpInst::ICMP_UGE:
5773 // (float)int >= -4.4 --> true
5774 // (float)int >= 4.4 --> int > 4
5775 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005777 Pred = ICmpInst::ICMP_UGT;
5778 break;
5779 case ICmpInst::ICMP_SGE:
5780 // (float)int >= -4.4 --> int >= -4
5781 // (float)int >= 4.4 --> int > 4
5782 if (!RHS.isNegative())
5783 Pred = ICmpInst::ICMP_SGT;
5784 break;
5785 }
Chris Lattnera5406232008-05-19 20:18:56 +00005786 }
5787 }
5788
5789 // Lower this FP comparison into an appropriate integer version of the
5790 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005791 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005792}
5793
Reid Spencere4d87aa2006-12-23 06:05:41 +00005794Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5795 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005796 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005797
Chris Lattner58e97462007-01-14 19:42:17 +00005798 // Fold trivial predicates.
5799 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005800 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005801 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005802 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005803
5804 // Simplify 'fcmp pred X, X'
5805 if (Op0 == Op1) {
5806 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005807 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005808 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5809 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5810 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005811 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005812 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5813 case FCmpInst::FCMP_OLT: // True if ordered and less than
5814 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005815 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005816
5817 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5818 case FCmpInst::FCMP_ULT: // True if unordered or less than
5819 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5820 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5821 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5822 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005823 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005824 return &I;
5825
5826 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5827 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5828 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5829 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5830 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5831 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005832 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005833 return &I;
5834 }
5835 }
5836
Reid Spencere4d87aa2006-12-23 06:05:41 +00005837 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005838 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005839
Reid Spencere4d87aa2006-12-23 06:05:41 +00005840 // Handle fcmp with constant RHS
5841 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005842 // If the constant is a nan, see if we can fold the comparison based on it.
5843 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5844 if (CFP->getValueAPF().isNaN()) {
5845 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005846 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005847 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5848 "Comparison must be either ordered or unordered!");
5849 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005850 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005851 }
5852 }
5853
Reid Spencere4d87aa2006-12-23 06:05:41 +00005854 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5855 switch (LHSI->getOpcode()) {
5856 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005857 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5858 // block. If in the same block, we're encouraging jump threading. If
5859 // not, we are just pessimizing the code by making an i1 phi.
5860 if (LHSI->getParent() == I.getParent())
5861 if (Instruction *NV = FoldOpIntoPhi(I))
5862 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005863 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005864 case Instruction::SIToFP:
5865 case Instruction::UIToFP:
5866 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5867 return NV;
5868 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005869 case Instruction::Select:
5870 // If either operand of the select is a constant, we can fold the
5871 // comparison into the select arms, which will cause one to be
5872 // constant folded and the select turned into a bitwise or.
5873 Value *Op1 = 0, *Op2 = 0;
5874 if (LHSI->hasOneUse()) {
5875 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5876 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005877 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005878 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005879 Op2 = Builder->CreateFCmp(I.getPredicate(),
5880 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005881 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5882 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005883 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005884 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005885 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5886 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005887 }
5888 }
5889
5890 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005891 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005892 break;
5893 }
5894 }
5895
5896 return Changed ? &I : 0;
5897}
5898
5899Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5900 bool Changed = SimplifyCompare(I);
5901 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5902 const Type *Ty = Op0->getType();
5903
5904 // icmp X, X
5905 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005906 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005907 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005908
5909 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005910 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005911
Reid Spencere4d87aa2006-12-23 06:05:41 +00005912 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005913 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005914 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5915 isa<ConstantPointerNull>(Op0)) &&
5916 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005917 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005918 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005919 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005920
Reid Spencere4d87aa2006-12-23 06:05:41 +00005921 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005922 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005923 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005924 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005925 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005926 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005927 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005928 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005929 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005930 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005931
Reid Spencere4d87aa2006-12-23 06:05:41 +00005932 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005933 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005934 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005935 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005936 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005937 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005938 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005939 case ICmpInst::ICMP_SGT:
5940 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005941 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005942 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005943 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005944 return BinaryOperator::CreateAnd(Not, Op0);
5945 }
5946 case ICmpInst::ICMP_UGE:
5947 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5948 // FALL THROUGH
5949 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005950 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005951 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005952 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005953 case ICmpInst::ICMP_SGE:
5954 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5955 // FALL THROUGH
5956 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005957 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005958 return BinaryOperator::CreateOr(Not, Op0);
5959 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005960 }
Chris Lattner8b170942002-08-09 23:47:40 +00005961 }
5962
Dan Gohman1c8491e2009-04-25 17:12:48 +00005963 unsigned BitWidth = 0;
5964 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005965 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5966 else if (Ty->isIntOrIntVector())
5967 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005968
5969 bool isSignBit = false;
5970
Dan Gohman81b28ce2008-09-16 18:46:06 +00005971 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005972 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005973 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005974
Chris Lattnerb6566012008-01-05 01:18:20 +00005975 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5976 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005977 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005978 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005979 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005980 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005981
Dan Gohman81b28ce2008-09-16 18:46:06 +00005982 // If we have an icmp le or icmp ge instruction, turn it into the
5983 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5984 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005985 switch (I.getPredicate()) {
5986 default: break;
5987 case ICmpInst::ICMP_ULE:
5988 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005989 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005990 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005991 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005992 case ICmpInst::ICMP_SLE:
5993 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005994 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005995 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005996 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005997 case ICmpInst::ICMP_UGE:
5998 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005999 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006000 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006001 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006002 case ICmpInst::ICMP_SGE:
6003 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006004 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006005 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006006 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006007 }
6008
Chris Lattner183661e2008-07-11 05:40:05 +00006009 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006010 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006011 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006012 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6013 }
6014
6015 // See if we can fold the comparison based on range information we can get
6016 // by checking whether bits are known to be zero or one in the input.
6017 if (BitWidth != 0) {
6018 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6019 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6020
6021 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006022 isSignBit ? APInt::getSignBit(BitWidth)
6023 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006024 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006025 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006026 if (SimplifyDemandedBits(I.getOperandUse(1),
6027 APInt::getAllOnesValue(BitWidth),
6028 Op1KnownZero, Op1KnownOne, 0))
6029 return &I;
6030
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006031 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006032 // in. Compute the Min, Max and RHS values based on the known bits. For the
6033 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006034 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6035 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6036 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6037 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6038 Op0Min, Op0Max);
6039 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6040 Op1Min, Op1Max);
6041 } else {
6042 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6043 Op0Min, Op0Max);
6044 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6045 Op1Min, Op1Max);
6046 }
6047
Chris Lattner183661e2008-07-11 05:40:05 +00006048 // If Min and Max are known to be the same, then SimplifyDemandedBits
6049 // figured out that the LHS is a constant. Just constant fold this now so
6050 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006051 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006052 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006053 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006054 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006055 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006056 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006057
Chris Lattner183661e2008-07-11 05:40:05 +00006058 // Based on the range information we know about the LHS, see if we can
6059 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006060 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006061 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006062 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006063 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006064 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006065 break;
6066 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006067 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006068 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006069 break;
6070 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006071 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006072 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006073 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006074 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006075 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006076 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006077 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6078 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006079 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006080 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006081
6082 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6083 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006084 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006085 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 }
Chris Lattner84dff672008-07-11 05:08:55 +00006087 break;
6088 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006089 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006091 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006092 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006093
6094 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006095 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006096 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6097 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006098 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006099 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006100
6101 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6102 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006103 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006104 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006105 }
Chris Lattner84dff672008-07-11 05:08:55 +00006106 break;
6107 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006108 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006109 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006110 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006111 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006113 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6115 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006116 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006117 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006118 }
Chris Lattner84dff672008-07-11 05:08:55 +00006119 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006120 case ICmpInst::ICMP_SGT:
6121 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006122 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006123 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006124 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006125
6126 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006127 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6129 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006130 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006131 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006132 }
6133 break;
6134 case ICmpInst::ICMP_SGE:
6135 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6136 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006137 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006138 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006139 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006140 break;
6141 case ICmpInst::ICMP_SLE:
6142 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6143 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006145 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006147 break;
6148 case ICmpInst::ICMP_UGE:
6149 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6150 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006151 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006152 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006153 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006154 break;
6155 case ICmpInst::ICMP_ULE:
6156 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6157 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006158 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006159 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006160 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006161 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006162 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006163
6164 // Turn a signed comparison into an unsigned one if both operands
6165 // are known to have the same sign.
6166 if (I.isSignedPredicate() &&
6167 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6168 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006169 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006170 }
6171
6172 // Test if the ICmpInst instruction is used exclusively by a select as
6173 // part of a minimum or maximum operation. If so, refrain from doing
6174 // any other folding. This helps out other analyses which understand
6175 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6176 // and CodeGen. And in this case, at least one of the comparison
6177 // operands has at least one user besides the compare (the select),
6178 // which would often largely negate the benefit of folding anyway.
6179 if (I.hasOneUse())
6180 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6181 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6182 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6183 return 0;
6184
6185 // See if we are doing a comparison between a constant and an instruction that
6186 // can be folded into the comparison.
6187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006188 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006189 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006190 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006191 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006192 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6193 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006194 }
6195
Chris Lattner01deb9d2007-04-03 17:43:25 +00006196 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006197 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6198 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6199 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006200 case Instruction::GetElementPtr:
6201 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006202 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006203 bool isAllZeros = true;
6204 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6205 if (!isa<Constant>(LHSI->getOperand(i)) ||
6206 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6207 isAllZeros = false;
6208 break;
6209 }
6210 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006211 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006212 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006213 }
6214 break;
6215
Chris Lattner6970b662005-04-23 15:31:55 +00006216 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006217 // Only fold icmp into the PHI if the phi and fcmp are in the same
6218 // block. If in the same block, we're encouraging jump threading. If
6219 // not, we are just pessimizing the code by making an i1 phi.
6220 if (LHSI->getParent() == I.getParent())
6221 if (Instruction *NV = FoldOpIntoPhi(I))
6222 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006223 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006224 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006225 // If either operand of the select is a constant, we can fold the
6226 // comparison into the select arms, which will cause one to be
6227 // constant folded and the select turned into a bitwise or.
6228 Value *Op1 = 0, *Op2 = 0;
6229 if (LHSI->hasOneUse()) {
6230 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6231 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006232 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006233 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006234 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6235 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006236 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6237 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006238 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006239 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006240 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6241 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006242 }
6243 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006244
Chris Lattner6970b662005-04-23 15:31:55 +00006245 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006246 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006247 break;
6248 }
Chris Lattner4802d902007-04-06 18:57:34 +00006249 case Instruction::Malloc:
6250 // If we have (malloc != null), and if the malloc has a single use, we
6251 // can assume it is successful and remove the malloc.
6252 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006253 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006254 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006255 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006256 }
6257 break;
6258 }
Chris Lattner6970b662005-04-23 15:31:55 +00006259 }
6260
Reid Spencere4d87aa2006-12-23 06:05:41 +00006261 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006262 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006263 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006264 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006265 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006266 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6267 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006268 return NI;
6269
Reid Spencere4d87aa2006-12-23 06:05:41 +00006270 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006271 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6272 // now.
6273 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6274 if (isa<PointerType>(Op0->getType()) &&
6275 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006276 // We keep moving the cast from the left operand over to the right
6277 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006278 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006279
Chris Lattner57d86372007-01-06 01:45:59 +00006280 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6281 // so eliminate it as well.
6282 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6283 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006284
Chris Lattnerde90b762003-11-03 04:25:02 +00006285 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006286 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006287 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006288 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006289 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006290 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006291 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006292 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006293 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006294 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006295 }
Chris Lattner57d86372007-01-06 01:45:59 +00006296 }
6297
6298 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006299 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006300 // This comes up when you have code like
6301 // int X = A < B;
6302 // if (X) ...
6303 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006304 // with a constant or another cast from the same type.
6305 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006306 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006307 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006308 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006309
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006310 // See if it's the same type of instruction on the left and right.
6311 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6312 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006313 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006314 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006315 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006316 default: break;
6317 case Instruction::Add:
6318 case Instruction::Sub:
6319 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006320 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006321 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006322 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006323 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6324 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6325 if (CI->getValue().isSignBit()) {
6326 ICmpInst::Predicate Pred = I.isSignedPredicate()
6327 ? I.getUnsignedPredicate()
6328 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006329 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006330 Op1I->getOperand(0));
6331 }
6332
6333 if (CI->getValue().isMaxSignedValue()) {
6334 ICmpInst::Predicate Pred = I.isSignedPredicate()
6335 ? I.getUnsignedPredicate()
6336 : I.getSignedPredicate();
6337 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006338 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006339 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006340 }
6341 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006342 break;
6343 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006344 if (!I.isEquality())
6345 break;
6346
Nick Lewycky5d52c452008-08-21 05:56:10 +00006347 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6348 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6349 // Mask = -1 >> count-trailing-zeros(Cst).
6350 if (!CI->isZero() && !CI->isOne()) {
6351 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006352 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006353 APInt::getLowBitsSet(AP.getBitWidth(),
6354 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006355 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006356 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6357 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006358 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006359 }
6360 }
6361 break;
6362 }
6363 }
6364 }
6365 }
6366
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006367 // ~x < ~y --> y < x
6368 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006369 if (match(Op0, m_Not(m_Value(A))) &&
6370 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006371 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006372 }
6373
Chris Lattner65b72ba2006-09-18 04:22:48 +00006374 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006375 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006376
6377 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006378 if (match(Op0, m_Neg(m_Value(A))) &&
6379 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006380 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006381
Dan Gohman4ae51262009-08-12 16:23:25 +00006382 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006383 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6384 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006385 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006386 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006387 }
6388
Dan Gohman4ae51262009-08-12 16:23:25 +00006389 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006390 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006391 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006392 if (match(B, m_ConstantInt(C1)) &&
6393 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006394 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006395 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006396 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6397 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006398 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006399
6400 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006401 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6402 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6403 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6404 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006405 }
6406 }
6407
Dan Gohman4ae51262009-08-12 16:23:25 +00006408 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006409 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006410 // A == (A^B) -> B == 0
6411 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006412 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006413 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006414 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006415
6416 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006417 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006418 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006419 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006420
6421 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006422 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006423 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006424 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006425
Chris Lattner9c2328e2006-11-14 06:06:06 +00006426 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6427 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006428 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6429 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006430 Value *X = 0, *Y = 0, *Z = 0;
6431
6432 if (A == C) {
6433 X = B; Y = D; Z = A;
6434 } else if (A == D) {
6435 X = B; Y = C; Z = A;
6436 } else if (B == C) {
6437 X = A; Y = D; Z = B;
6438 } else if (B == D) {
6439 X = A; Y = C; Z = B;
6440 }
6441
6442 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006443 Op1 = Builder->CreateXor(X, Y, "tmp");
6444 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006445 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006446 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006447 return &I;
6448 }
6449 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006450 }
Chris Lattner7e708292002-06-25 16:13:24 +00006451 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006452}
6453
Chris Lattner562ef782007-06-20 23:46:26 +00006454
6455/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6456/// and CmpRHS are both known to be integer constants.
6457Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6458 ConstantInt *DivRHS) {
6459 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6460 const APInt &CmpRHSV = CmpRHS->getValue();
6461
6462 // FIXME: If the operand types don't match the type of the divide
6463 // then don't attempt this transform. The code below doesn't have the
6464 // logic to deal with a signed divide and an unsigned compare (and
6465 // vice versa). This is because (x /s C1) <s C2 produces different
6466 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6467 // (x /u C1) <u C2. Simply casting the operands and result won't
6468 // work. :( The if statement below tests that condition and bails
6469 // if it finds it.
6470 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6471 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6472 return 0;
6473 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006474 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006475 if (DivIsSigned && DivRHS->isAllOnesValue())
6476 return 0; // The overflow computation also screws up here
6477 if (DivRHS->isOne())
6478 return 0; // Not worth bothering, and eliminates some funny cases
6479 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006480
6481 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6482 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6483 // C2 (CI). By solving for X we can turn this into a range check
6484 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006485 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006486
6487 // Determine if the product overflows by seeing if the product is
6488 // not equal to the divide. Make sure we do the same kind of divide
6489 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006490 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6491 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006492
6493 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006494 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006495
Chris Lattner1dbfd482007-06-21 18:11:19 +00006496 // Figure out the interval that is being checked. For example, a comparison
6497 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6498 // Compute this interval based on the constants involved and the signedness of
6499 // the compare/divide. This computes a half-open interval, keeping track of
6500 // whether either value in the interval overflows. After analysis each
6501 // overflow variable is set to 0 if it's corresponding bound variable is valid
6502 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6503 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006504 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006505
Chris Lattner562ef782007-06-20 23:46:26 +00006506 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006507 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006508 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006509 HiOverflow = LoOverflow = ProdOV;
6510 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006511 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006512 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006513 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006514 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006515 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006516 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006517 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006518 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6519 HiOverflow = LoOverflow = ProdOV;
6520 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006521 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006522 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006523 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006524 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006525 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6526 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006527 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006528 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006529 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006530 true) ? -1 : 0;
6531 }
Chris Lattner562ef782007-06-20 23:46:26 +00006532 }
Dan Gohman76491272008-02-13 22:09:18 +00006533 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006534 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006535 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006536 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006537 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006538 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6539 HiOverflow = 1; // [INTMIN+1, overflow)
6540 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6541 }
Dan Gohman76491272008-02-13 22:09:18 +00006542 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006543 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006544 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006545 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006546 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006547 LoOverflow = AddWithOverflow(LoBound, HiBound,
6548 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006549 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006550 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6551 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006552 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006553 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006554 }
6555
Chris Lattner1dbfd482007-06-21 18:11:19 +00006556 // Dividing by a negative swaps the condition. LT <-> GT
6557 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006558 }
6559
6560 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006561 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006562 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006563 case ICmpInst::ICMP_EQ:
6564 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006565 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006566 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006567 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006568 ICmpInst::ICMP_UGE, X, LoBound);
6569 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006570 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006571 ICmpInst::ICMP_ULT, X, HiBound);
6572 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006573 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006574 case ICmpInst::ICMP_NE:
6575 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006576 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006577 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006578 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006579 ICmpInst::ICMP_ULT, X, LoBound);
6580 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006581 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006582 ICmpInst::ICMP_UGE, X, HiBound);
6583 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006584 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006585 case ICmpInst::ICMP_ULT:
6586 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006587 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006588 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006589 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006590 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006591 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006592 case ICmpInst::ICMP_UGT:
6593 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006594 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006595 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006596 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006597 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006598 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006599 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006600 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006601 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006602 }
6603}
6604
6605
Chris Lattner01deb9d2007-04-03 17:43:25 +00006606/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6607///
6608Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6609 Instruction *LHSI,
6610 ConstantInt *RHS) {
6611 const APInt &RHSV = RHS->getValue();
6612
6613 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006614 case Instruction::Trunc:
6615 if (ICI.isEquality() && LHSI->hasOneUse()) {
6616 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6617 // of the high bits truncated out of x are known.
6618 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6619 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6620 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6621 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6622 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6623
6624 // If all the high bits are known, we can do this xform.
6625 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6626 // Pull in the high bits from known-ones set.
6627 APInt NewRHS(RHS->getValue());
6628 NewRHS.zext(SrcBits);
6629 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006630 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006631 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006632 }
6633 }
6634 break;
6635
Duncan Sands0091bf22007-04-04 06:42:45 +00006636 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006637 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6638 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6639 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006640 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6641 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006642 Value *CompareVal = LHSI->getOperand(0);
6643
6644 // If the sign bit of the XorCST is not set, there is no change to
6645 // the operation, just stop using the Xor.
6646 if (!XorCST->getValue().isNegative()) {
6647 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006648 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006649 return &ICI;
6650 }
6651
6652 // Was the old condition true if the operand is positive?
6653 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6654
6655 // If so, the new one isn't.
6656 isTrueIfPositive ^= true;
6657
6658 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006659 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006660 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006661 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006662 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006663 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006664 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006665
6666 if (LHSI->hasOneUse()) {
6667 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6668 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6669 const APInt &SignBit = XorCST->getValue();
6670 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6671 ? ICI.getUnsignedPredicate()
6672 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006673 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006674 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006675 }
6676
6677 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006678 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006679 const APInt &NotSignBit = XorCST->getValue();
6680 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6681 ? ICI.getUnsignedPredicate()
6682 : ICI.getSignedPredicate();
6683 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006684 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006685 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006686 }
6687 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006688 }
6689 break;
6690 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6691 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6692 LHSI->getOperand(0)->hasOneUse()) {
6693 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6694
6695 // If the LHS is an AND of a truncating cast, we can widen the
6696 // and/compare to be the input width without changing the value
6697 // produced, eliminating a cast.
6698 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6699 // We can do this transformation if either the AND constant does not
6700 // have its sign bit set or if it is an equality comparison.
6701 // Extending a relational comparison when we're checking the sign
6702 // bit would not work.
6703 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006704 (ICI.isEquality() ||
6705 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006706 uint32_t BitWidth =
6707 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6708 APInt NewCST = AndCST->getValue();
6709 NewCST.zext(BitWidth);
6710 APInt NewCI = RHSV;
6711 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006712 Value *NewAnd =
6713 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006714 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006715 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006716 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006717 }
6718 }
6719
6720 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6721 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6722 // happens a LOT in code produced by the C front-end, for bitfield
6723 // access.
6724 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6725 if (Shift && !Shift->isShift())
6726 Shift = 0;
6727
6728 ConstantInt *ShAmt;
6729 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6730 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6731 const Type *AndTy = AndCST->getType(); // Type of the and.
6732
6733 // We can fold this as long as we can't shift unknown bits
6734 // into the mask. This can only happen with signed shift
6735 // rights, as they sign-extend.
6736 if (ShAmt) {
6737 bool CanFold = Shift->isLogicalShift();
6738 if (!CanFold) {
6739 // To test for the bad case of the signed shr, see if any
6740 // of the bits shifted in could be tested after the mask.
6741 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6742 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6743
6744 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6745 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6746 AndCST->getValue()) == 0)
6747 CanFold = true;
6748 }
6749
6750 if (CanFold) {
6751 Constant *NewCst;
6752 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006753 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006754 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006755 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006756
6757 // Check to see if we are shifting out any of the bits being
6758 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006759 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006760 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006761 // If we shifted bits out, the fold is not going to work out.
6762 // As a special case, check to see if this means that the
6763 // result is always true or false now.
6764 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006765 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006766 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006767 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006768 } else {
6769 ICI.setOperand(1, NewCst);
6770 Constant *NewAndCST;
6771 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006772 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006773 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006774 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775 LHSI->setOperand(1, NewAndCST);
6776 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006777 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006778 return &ICI;
6779 }
6780 }
6781 }
6782
6783 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6784 // preferable because it allows the C<<Y expression to be hoisted out
6785 // of a loop if Y is invariant and X is not.
6786 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006787 ICI.isEquality() && !Shift->isArithmeticShift() &&
6788 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006789 // Compute C << Y.
6790 Value *NS;
6791 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006792 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006793 } else {
6794 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006795 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006796 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006797
6798 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006799 Value *NewAnd =
6800 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006801
6802 ICI.setOperand(0, NewAnd);
6803 return &ICI;
6804 }
6805 }
6806 break;
6807
Chris Lattnera0141b92007-07-15 20:42:37 +00006808 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6809 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6810 if (!ShAmt) break;
6811
6812 uint32_t TypeBits = RHSV.getBitWidth();
6813
6814 // Check that the shift amount is in range. If not, don't perform
6815 // undefined shifts. When the shift is visited it will be
6816 // simplified.
6817 if (ShAmt->uge(TypeBits))
6818 break;
6819
6820 if (ICI.isEquality()) {
6821 // If we are comparing against bits always shifted out, the
6822 // comparison cannot succeed.
6823 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006824 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006825 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006826 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6827 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006828 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006829 return ReplaceInstUsesWith(ICI, Cst);
6830 }
6831
6832 if (LHSI->hasOneUse()) {
6833 // Otherwise strength reduce the shift into an and.
6834 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6835 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006836 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006837 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006838
Chris Lattner74381062009-08-30 07:44:24 +00006839 Value *And =
6840 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006841 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006842 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006843 }
6844 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006845
6846 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6847 bool TrueIfSigned = false;
6848 if (LHSI->hasOneUse() &&
6849 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6850 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006851 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006852 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006853 Value *And =
6854 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006855 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006856 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006857 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006858 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006859 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006860
6861 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006862 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006863 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006864 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006865 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006866
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006867 // Check that the shift amount is in range. If not, don't perform
6868 // undefined shifts. When the shift is visited it will be
6869 // simplified.
6870 uint32_t TypeBits = RHSV.getBitWidth();
6871 if (ShAmt->uge(TypeBits))
6872 break;
6873
6874 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006875
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006876 // If we are comparing against bits always shifted out, the
6877 // comparison cannot succeed.
6878 APInt Comp = RHSV << ShAmtVal;
6879 if (LHSI->getOpcode() == Instruction::LShr)
6880 Comp = Comp.lshr(ShAmtVal);
6881 else
6882 Comp = Comp.ashr(ShAmtVal);
6883
6884 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6885 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006886 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006887 return ReplaceInstUsesWith(ICI, Cst);
6888 }
6889
6890 // Otherwise, check to see if the bits shifted out are known to be zero.
6891 // If so, we can compare against the unshifted value:
6892 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006893 if (LHSI->hasOneUse() &&
6894 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006895 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006896 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006897 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006898 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006899
Evan Chengf30752c2008-04-23 00:38:06 +00006900 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006901 // Otherwise strength reduce the shift into an and.
6902 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006903 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006904
Chris Lattner74381062009-08-30 07:44:24 +00006905 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6906 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006907 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006908 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006909 }
6910 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006911 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006912
6913 case Instruction::SDiv:
6914 case Instruction::UDiv:
6915 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6916 // Fold this div into the comparison, producing a range check.
6917 // Determine, based on the divide type, what the range is being
6918 // checked. If there is an overflow on the low or high side, remember
6919 // it, otherwise compute the range [low, hi) bounding the new value.
6920 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006921 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6922 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6923 DivRHS))
6924 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006925 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006926
6927 case Instruction::Add:
6928 // Fold: icmp pred (add, X, C1), C2
6929
6930 if (!ICI.isEquality()) {
6931 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6932 if (!LHSC) break;
6933 const APInt &LHSV = LHSC->getValue();
6934
6935 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6936 .subtract(LHSV);
6937
6938 if (ICI.isSignedPredicate()) {
6939 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006940 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006941 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006942 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006943 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006944 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006945 }
6946 } else {
6947 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006948 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006949 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006950 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006951 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006952 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006953 }
6954 }
6955 }
6956 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006957 }
6958
6959 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6960 if (ICI.isEquality()) {
6961 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6962
6963 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6964 // the second operand is a constant, simplify a bit.
6965 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6966 switch (BO->getOpcode()) {
6967 case Instruction::SRem:
6968 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6969 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6970 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6971 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006972 Value *NewRem =
6973 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6974 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006975 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006976 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006977 }
6978 }
6979 break;
6980 case Instruction::Add:
6981 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6982 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6983 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006984 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006985 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006986 } else if (RHSV == 0) {
6987 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6988 // efficiently invertible, or if the add has just this one use.
6989 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6990
Dan Gohman186a6362009-08-12 16:04:34 +00006991 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006992 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006993 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006994 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006995 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006996 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006997 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006998 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006999 }
7000 }
7001 break;
7002 case Instruction::Xor:
7003 // For the xor case, we can xor two constants together, eliminating
7004 // the explicit xor.
7005 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007006 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007007 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007008
7009 // FALLTHROUGH
7010 case Instruction::Sub:
7011 // Replace (([sub|xor] A, B) != 0) with (A != B)
7012 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007013 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007014 BO->getOperand(1));
7015 break;
7016
7017 case Instruction::Or:
7018 // If bits are being or'd in that are not present in the constant we
7019 // are comparing against, then the comparison could never succeed!
7020 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007021 Constant *NotCI = ConstantExpr::getNot(RHS);
7022 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007023 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007024 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007025 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007026 }
7027 break;
7028
7029 case Instruction::And:
7030 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7031 // If bits are being compared against that are and'd out, then the
7032 // comparison can never succeed!
7033 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007034 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007035 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007036 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007037
7038 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7039 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007040 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007041 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007042 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007043
7044 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007045 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007046 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007047 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007048 ICmpInst::Predicate pred = isICMP_NE ?
7049 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007050 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007051 }
7052
7053 // ((X & ~7) == 0) --> X < 8
7054 if (RHSV == 0 && isHighOnes(BOC)) {
7055 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007056 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007057 ICmpInst::Predicate pred = isICMP_NE ?
7058 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007059 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007060 }
7061 }
7062 default: break;
7063 }
7064 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7065 // Handle icmp {eq|ne} <intrinsic>, intcst.
7066 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007067 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007068 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007069 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007070 return &ICI;
7071 }
7072 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007073 }
7074 return 0;
7075}
7076
7077/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7078/// We only handle extending casts so far.
7079///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007080Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7081 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007082 Value *LHSCIOp = LHSCI->getOperand(0);
7083 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007084 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007085 Value *RHSCIOp;
7086
Chris Lattner8c756c12007-05-05 22:41:33 +00007087 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7088 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007089 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7090 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007091 cast<IntegerType>(DestTy)->getBitWidth()) {
7092 Value *RHSOp = 0;
7093 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007094 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007095 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7096 RHSOp = RHSC->getOperand(0);
7097 // If the pointer types don't match, insert a bitcast.
7098 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007099 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007100 }
7101
7102 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007103 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007104 }
7105
7106 // The code below only handles extension cast instructions, so far.
7107 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007108 if (LHSCI->getOpcode() != Instruction::ZExt &&
7109 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007110 return 0;
7111
Reid Spencere4d87aa2006-12-23 06:05:41 +00007112 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7113 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007114
Reid Spencere4d87aa2006-12-23 06:05:41 +00007115 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007116 // Not an extension from the same type?
7117 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007118 if (RHSCIOp->getType() != LHSCIOp->getType())
7119 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007120
Nick Lewycky4189a532008-01-28 03:48:02 +00007121 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007122 // and the other is a zext), then we can't handle this.
7123 if (CI->getOpcode() != LHSCI->getOpcode())
7124 return 0;
7125
Nick Lewycky4189a532008-01-28 03:48:02 +00007126 // Deal with equality cases early.
7127 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007128 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007129
7130 // A signed comparison of sign extended values simplifies into a
7131 // signed comparison.
7132 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007133 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007134
7135 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007136 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007137 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007138
Reid Spencere4d87aa2006-12-23 06:05:41 +00007139 // If we aren't dealing with a constant on the RHS, exit early
7140 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7141 if (!CI)
7142 return 0;
7143
7144 // Compute the constant that would happen if we truncated to SrcTy then
7145 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007146 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7147 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007148 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007149
7150 // If the re-extended constant didn't change...
7151 if (Res2 == CI) {
7152 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7153 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007154 // %A = sext i16 %X to i32
7155 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007156 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007157 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007158 // because %A may have negative value.
7159 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007160 // However, we allow this when the compare is EQ/NE, because they are
7161 // signless.
7162 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007163 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007164 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007165 }
7166
7167 // The re-extended constant changed so the constant cannot be represented
7168 // in the shorter type. Consequently, we cannot emit a simple comparison.
7169
7170 // First, handle some easy cases. We know the result cannot be equal at this
7171 // point so handle the ICI.isEquality() cases
7172 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007173 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007174 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007175 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007176
7177 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7178 // should have been folded away previously and not enter in here.
7179 Value *Result;
7180 if (isSignedCmp) {
7181 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007182 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007183 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007184 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007185 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007186 } else {
7187 // We're performing an unsigned comparison.
7188 if (isSignedExt) {
7189 // We're performing an unsigned comp with a sign extended value.
7190 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007191 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007192 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007193 } else {
7194 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007195 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007196 }
7197 }
7198
7199 // Finally, return the value computed.
7200 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007201 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007202 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007203
7204 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7205 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7206 "ICmp should be folded!");
7207 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007208 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007209 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007210}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007211
Reid Spencer832254e2007-02-02 02:16:23 +00007212Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7213 return commonShiftTransforms(I);
7214}
7215
7216Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7217 return commonShiftTransforms(I);
7218}
7219
7220Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007221 if (Instruction *R = commonShiftTransforms(I))
7222 return R;
7223
7224 Value *Op0 = I.getOperand(0);
7225
7226 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7227 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7228 if (CSI->isAllOnesValue())
7229 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007230
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007231 // See if we can turn a signed shr into an unsigned shr.
7232 if (MaskedValueIsZero(Op0,
7233 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7234 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7235
7236 // Arithmetic shifting an all-sign-bit value is a no-op.
7237 unsigned NumSignBits = ComputeNumSignBits(Op0);
7238 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7239 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007240
Chris Lattner348f6652007-12-06 01:59:46 +00007241 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007242}
7243
7244Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7245 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007246 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007247
7248 // shl X, 0 == X and shr X, 0 == X
7249 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007250 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7251 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007252 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007253
Reid Spencere4d87aa2006-12-23 06:05:41 +00007254 if (isa<UndefValue>(Op0)) {
7255 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007256 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007257 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007258 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007259 }
7260 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007261 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7262 return ReplaceInstUsesWith(I, Op0);
7263 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007264 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007265 }
7266
Dan Gohman9004c8a2009-05-21 02:28:33 +00007267 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007268 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007269 return &I;
7270
Chris Lattner2eefe512004-04-09 19:05:30 +00007271 // Try to fold constant and into select arguments.
7272 if (isa<Constant>(Op0))
7273 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007274 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007275 return R;
7276
Reid Spencerb83eb642006-10-20 07:07:24 +00007277 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007278 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7279 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007280 return 0;
7281}
7282
Reid Spencerb83eb642006-10-20 07:07:24 +00007283Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007284 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007285 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007286
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007287 // See if we can simplify any instructions used by the instruction whose sole
7288 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007289 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007290
Dan Gohmana119de82009-06-14 23:30:43 +00007291 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7292 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007293 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007294 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007295 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007296 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007297 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007298 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007299 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007300 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007301 }
7302
7303 // ((X*C1) << C2) == (X * (C1 << C2))
7304 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7305 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7306 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007307 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007308 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007309
7310 // Try to fold constant and into select arguments.
7311 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7313 return R;
7314 if (isa<PHINode>(Op0))
7315 if (Instruction *NV = FoldOpIntoPhi(I))
7316 return NV;
7317
Chris Lattner8999dd32007-12-22 09:07:47 +00007318 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7319 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7320 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7321 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7322 // place. Don't try to do this transformation in this case. Also, we
7323 // require that the input operand is a shift-by-constant so that we have
7324 // confidence that the shifts will get folded together. We could do this
7325 // xform in more cases, but it is unlikely to be profitable.
7326 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7327 isa<ConstantInt>(TrOp->getOperand(1))) {
7328 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007329 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007330 // (shift2 (shift1 & 0x00FF), c2)
7331 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007332
7333 // For logical shifts, the truncation has the effect of making the high
7334 // part of the register be zeros. Emulate this by inserting an AND to
7335 // clear the top bits as needed. This 'and' will usually be zapped by
7336 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007337 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7338 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007339 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7340
7341 // The mask we constructed says what the trunc would do if occurring
7342 // between the shifts. We want to know the effect *after* the second
7343 // shift. We know that it is a logical shift by a constant, so adjust the
7344 // mask as appropriate.
7345 if (I.getOpcode() == Instruction::Shl)
7346 MaskV <<= Op1->getZExtValue();
7347 else {
7348 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7349 MaskV = MaskV.lshr(Op1->getZExtValue());
7350 }
7351
Chris Lattner74381062009-08-30 07:44:24 +00007352 // shift1 & 0x00FF
7353 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7354 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007355
7356 // Return the value truncated to the interesting size.
7357 return new TruncInst(And, I.getType());
7358 }
7359 }
7360
Chris Lattner4d5542c2006-01-06 07:12:35 +00007361 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007362 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7363 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7364 Value *V1, *V2;
7365 ConstantInt *CC;
7366 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007367 default: break;
7368 case Instruction::Add:
7369 case Instruction::And:
7370 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007371 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007372 // These operators commute.
7373 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007374 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007375 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007376 m_Specific(Op1)))){
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007377 Instruction *YS = BinaryOperator::CreateShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00007378 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00007379 Op0BO->getName());
7380 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007381 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007382 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007383 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007384 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007385 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007386 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007387 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007388 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007389
Chris Lattner150f12a2005-09-18 06:30:59 +00007390 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007391 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007392 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007393 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007394 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007395 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007396 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007397 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007398 Op0BO->getOperand(0), Op1,
7399 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007400 InsertNewInstBefore(YS, I); // (Y << C)
7401 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007402 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007403 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007404 V1->getName()+".mask");
7405 InsertNewInstBefore(XM, I); // X & (CC << C)
7406
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007407 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007408 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007409 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007410
Reid Spencera07cb7d2007-02-02 14:41:37 +00007411 // FALL THROUGH.
7412 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007413 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007414 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007415 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007416 m_Specific(Op1)))) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007417 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007418 Op0BO->getOperand(1), Op1,
7419 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007420 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007421 Instruction *X =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007422 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007423 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007424 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00007425 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007426 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007427 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007428 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007429
Chris Lattner13d4ab42006-05-31 21:14:00 +00007430 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007431 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7432 match(Op0BO->getOperand(0),
7433 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007434 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007435 cast<BinaryOperator>(Op0BO->getOperand(0))
7436 ->getOperand(0)->hasOneUse()) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007437 Instruction *YS = BinaryOperator::CreateShl(
Reid Spencer832254e2007-02-02 02:16:23 +00007438 Op0BO->getOperand(1), Op1,
7439 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00007440 InsertNewInstBefore(YS, I); // (Y << C)
7441 Instruction *XM =
Owen Andersond672ecb2009-07-03 00:17:18 +00007442 BinaryOperator::CreateAnd(V1,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007443 ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00007444 V1->getName()+".mask");
7445 InsertNewInstBefore(XM, I); // X & (CC << C)
7446
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007447 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007448 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007449
Chris Lattner11021cb2005-09-18 05:12:10 +00007450 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007451 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007452 }
7453
7454
7455 // If the operand is an bitwise operator with a constant RHS, and the
7456 // shift is the only use, we can pull it out of the shift.
7457 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7458 bool isValid = true; // Valid only for And, Or, Xor
7459 bool highBitSet = false; // Transform if high bit of constant set?
7460
7461 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007462 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007463 case Instruction::Add:
7464 isValid = isLeftShift;
7465 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007466 case Instruction::Or:
7467 case Instruction::Xor:
7468 highBitSet = false;
7469 break;
7470 case Instruction::And:
7471 highBitSet = true;
7472 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473 }
7474
7475 // If this is a signed shift right, and the high bit is modified
7476 // by the logical operation, do not perform the transformation.
7477 // The highBitSet boolean indicates the value of the high bit of
7478 // the constant which would cause it to be modified for this
7479 // operation.
7480 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007481 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007482 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007483
7484 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007485 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007486
7487 Instruction *NewShift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007488 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007489 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00007490 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007491
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007492 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007493 NewRHS);
7494 }
7495 }
7496 }
7497 }
7498
Chris Lattnerad0124c2006-01-06 07:52:12 +00007499 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007500 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7501 if (ShiftOp && !ShiftOp->isShift())
7502 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007503
Reid Spencerb83eb642006-10-20 07:07:24 +00007504 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007505 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007506 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7507 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007508 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7509 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7510 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007511
Zhou Sheng4351c642007-04-02 08:20:41 +00007512 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007513
7514 const IntegerType *Ty = cast<IntegerType>(I.getType());
7515
7516 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007517 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007518 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7519 // saturates.
7520 if (AmtSum >= TypeBits) {
7521 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007522 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007523 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7524 }
7525
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007526 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007527 ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007528 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7529 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007530 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007531 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007532
Chris Lattnerb87056f2007-02-05 00:57:54 +00007533 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007534 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007535 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7536 I.getOpcode() == Instruction::LShr) {
7537 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007538 if (AmtSum >= TypeBits)
7539 AmtSum = TypeBits-1;
7540
Chris Lattnerb87056f2007-02-05 00:57:54 +00007541 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007542 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007543 InsertNewInstBefore(Shift, I);
7544
Zhou Shenge9e03f62007-03-28 15:02:20 +00007545 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007546 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007547 }
7548
Chris Lattnerb87056f2007-02-05 00:57:54 +00007549 // Okay, if we get here, one shift must be left, and the other shift must be
7550 // right. See if the amounts are equal.
7551 if (ShiftAmt1 == ShiftAmt2) {
7552 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7553 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007554 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007555 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007556 }
7557 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7558 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007559 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007560 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007561 }
7562 // We can simplify ((X << C) >>s C) into a trunc + sext.
7563 // NOTE: we could do this for any C, but that would make 'unusual' integer
7564 // types. For now, just stick to ones well-supported by the code
7565 // generators.
7566 const Type *SExtType = 0;
7567 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007568 case 1 :
7569 case 8 :
7570 case 16 :
7571 case 32 :
7572 case 64 :
7573 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007574 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007575 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007576 default: break;
7577 }
7578 if (SExtType) {
7579 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7580 InsertNewInstBefore(NewTrunc, I);
7581 return new SExtInst(NewTrunc, Ty);
7582 }
7583 // Otherwise, we can't handle it yet.
7584 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007585 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007586
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007587 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007588 if (I.getOpcode() == Instruction::Shl) {
7589 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7590 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00007591 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007592 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007593 InsertNewInstBefore(Shift, I);
7594
Reid Spencer55702aa2007-03-25 21:11:44 +00007595 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007596 return BinaryOperator::CreateAnd(Shift,
7597 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007598 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007600 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007601 if (I.getOpcode() == Instruction::LShr) {
7602 assert(ShiftOp->getOpcode() == Instruction::Shl);
7603 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007604 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007605 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007606
Reid Spencerd5e30f02007-03-26 17:18:58 +00007607 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007608 return BinaryOperator::CreateAnd(Shift,
7609 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007610 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007611
7612 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7613 } else {
7614 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007615 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007616
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007617 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 if (I.getOpcode() == Instruction::Shl) {
7619 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7620 ShiftOp->getOpcode() == Instruction::AShr);
7621 Instruction *Shift =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007622 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007623 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007624 InsertNewInstBefore(Shift, I);
7625
Reid Spencer55702aa2007-03-25 21:11:44 +00007626 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007627 return BinaryOperator::CreateAnd(Shift,
7628 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007629 }
7630
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007631 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007632 if (I.getOpcode() == Instruction::LShr) {
7633 assert(ShiftOp->getOpcode() == Instruction::Shl);
7634 Instruction *Shift =
Owen Andersoneed707b2009-07-24 23:12:02 +00007635 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007636 InsertNewInstBefore(Shift, I);
7637
Reid Spencer68d27cf2007-03-26 23:45:51 +00007638 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007639 return BinaryOperator::CreateAnd(Shift,
7640 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007641 }
7642
7643 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007644 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007645 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007646 return 0;
7647}
7648
Chris Lattnera1be5662002-05-02 17:06:02 +00007649
Chris Lattnercfd65102005-10-29 04:36:15 +00007650/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7651/// expression. If so, decompose it, returning some value X, such that Val is
7652/// X*Scale+Offset.
7653///
7654static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007655 int &Offset, LLVMContext *Context) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007656 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007657 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007658 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007659 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007660 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007661 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7662 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7663 if (I->getOpcode() == Instruction::Shl) {
7664 // This is a value scaled by '1 << the shift amt'.
7665 Scale = 1U << RHS->getZExtValue();
7666 Offset = 0;
7667 return I->getOperand(0);
7668 } else if (I->getOpcode() == Instruction::Mul) {
7669 // This value is scaled by 'RHS'.
7670 Scale = RHS->getZExtValue();
7671 Offset = 0;
7672 return I->getOperand(0);
7673 } else if (I->getOpcode() == Instruction::Add) {
7674 // We have X+C. Check to see if we really have (X*C2)+C1,
7675 // where C1 is divisible by C2.
7676 unsigned SubScale;
7677 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007678 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7679 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007680 Offset += RHS->getZExtValue();
7681 Scale = SubScale;
7682 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007683 }
7684 }
7685 }
7686
7687 // Otherwise, we can't look past this.
7688 Scale = 1;
7689 Offset = 0;
7690 return Val;
7691}
7692
7693
Chris Lattnerb3f83972005-10-24 06:03:58 +00007694/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7695/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007696Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007697 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007698 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007699
Chris Lattnerb53c2382005-10-24 06:22:12 +00007700 // Remove any uses of AI that are dead.
7701 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007702
Chris Lattnerb53c2382005-10-24 06:22:12 +00007703 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7704 Instruction *User = cast<Instruction>(*UI++);
7705 if (isInstructionTriviallyDead(User)) {
7706 while (UI != E && *UI == User)
7707 ++UI; // If this instruction uses AI more than once, don't break UI.
7708
Chris Lattnerb53c2382005-10-24 06:22:12 +00007709 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007710 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007711 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007712 }
7713 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007714
7715 // This requires TargetData to get the alloca alignment and size information.
7716 if (!TD) return 0;
7717
Chris Lattnerb3f83972005-10-24 06:03:58 +00007718 // Get the type really allocated and the type casted to.
7719 const Type *AllocElTy = AI.getAllocatedType();
7720 const Type *CastElTy = PTy->getElementType();
7721 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007722
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007723 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7724 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007725 if (CastElTyAlign < AllocElTyAlign) return 0;
7726
Chris Lattner39387a52005-10-24 06:35:18 +00007727 // If the allocation has multiple uses, only promote it if we are strictly
7728 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007729 // same, we open the door to infinite loops of various kinds. (A reference
7730 // from a dbg.declare doesn't count as a use for this purpose.)
7731 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7732 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007733
Duncan Sands777d2302009-05-09 07:06:46 +00007734 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7735 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007736 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007737
Chris Lattner455fcc82005-10-29 03:19:53 +00007738 // See if we can satisfy the modulus by pulling a scale out of the array
7739 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007740 unsigned ArraySizeScale;
7741 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007742 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007743 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7744 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007745
Chris Lattner455fcc82005-10-29 03:19:53 +00007746 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7747 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007748 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7749 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007750
Chris Lattner455fcc82005-10-29 03:19:53 +00007751 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7752 Value *Amt = 0;
7753 if (Scale == 1) {
7754 Amt = NumElements;
7755 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00007756 // If the allocation size is constant, form a constant mul expression
Owen Anderson1d0be152009-08-13 21:58:54 +00007757 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Reid Spencerc5b206b2006-12-31 05:48:39 +00007758 if (isa<ConstantInt>(NumElements))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007759 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
Dan Gohman6de29f82009-06-15 22:12:54 +00007760 cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00007761 // otherwise multiply the amount and the number of elements
Chris Lattner46d232d2009-03-17 17:55:15 +00007762 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007763 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Chris Lattner455fcc82005-10-29 03:19:53 +00007764 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00007765 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007766 }
7767
Jeff Cohen86796be2007-04-04 16:58:57 +00007768 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007769 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007770 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007771 Amt = InsertNewInstBefore(Tmp, AI);
7772 }
7773
Chris Lattnerb3f83972005-10-24 06:03:58 +00007774 AllocationInst *New;
7775 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +00007776 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007777 else
Owen Anderson50dead02009-07-15 23:53:25 +00007778 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007779 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00007780 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007781
Dale Johannesena0a66372009-03-05 00:39:02 +00007782 // If the allocation has one real use plus a dbg.declare, just remove the
7783 // declare.
7784 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7785 EraseInstFromFunction(*DI);
7786 }
7787 // If the allocation has multiple real uses, insert a cast and change all
7788 // things that used it to use the new cast. This will also hack on CI, but it
7789 // will die soon.
7790 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007791 // New is the allocation instruction, pointer typed. AI is the original
7792 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7793 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007794 InsertNewInstBefore(NewCast, AI);
7795 AI.replaceAllUsesWith(NewCast);
7796 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007797 return ReplaceInstUsesWith(CI, New);
7798}
7799
Chris Lattner70074e02006-05-13 02:06:03 +00007800/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007801/// and return it as type Ty without inserting any new casts and without
7802/// changing the computed value. This is used by code that tries to decide
7803/// whether promoting or shrinking integer operations to wider or smaller types
7804/// will allow us to eliminate a truncate or extend.
7805///
7806/// This is a truncation operation if Ty is smaller than V->getType(), or an
7807/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007808///
7809/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7810/// should return true if trunc(V) can be computed by computing V in the smaller
7811/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7812/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7813/// efficiently truncated.
7814///
7815/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7816/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7817/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007818bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007819 unsigned CastOpc,
7820 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007821 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007822 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007823 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007824
7825 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007826 if (!I) return false;
7827
Dan Gohman6de29f82009-06-15 22:12:54 +00007828 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007829
Chris Lattner951626b2007-08-02 06:11:14 +00007830 // If this is an extension or truncate, we can often eliminate it.
7831 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7832 // If this is a cast from the destination type, we can trivially eliminate
7833 // it, and this will remove a cast overall.
7834 if (I->getOperand(0)->getType() == Ty) {
7835 // If the first operand is itself a cast, and is eliminable, do not count
7836 // this as an eliminable cast. We would prefer to eliminate those two
7837 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007838 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007839 ++NumCastsRemoved;
7840 return true;
7841 }
7842 }
7843
7844 // We can't extend or shrink something that has multiple uses: doing so would
7845 // require duplicating the instruction in general, which isn't profitable.
7846 if (!I->hasOneUse()) return false;
7847
Evan Chengf35fd542009-01-15 17:01:23 +00007848 unsigned Opc = I->getOpcode();
7849 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007850 case Instruction::Add:
7851 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007852 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007853 case Instruction::And:
7854 case Instruction::Or:
7855 case Instruction::Xor:
7856 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007857 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007858 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007859 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007860 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007861
Eli Friedman070a9812009-07-13 22:46:01 +00007862 case Instruction::UDiv:
7863 case Instruction::URem: {
7864 // UDiv and URem can be truncated if all the truncated bits are zero.
7865 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7866 uint32_t BitWidth = Ty->getScalarSizeInBits();
7867 if (BitWidth < OrigBitWidth) {
7868 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7869 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7870 MaskedValueIsZero(I->getOperand(1), Mask)) {
7871 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7872 NumCastsRemoved) &&
7873 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7874 NumCastsRemoved);
7875 }
7876 }
7877 break;
7878 }
Chris Lattner46b96052006-11-29 07:18:39 +00007879 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007880 // If we are truncating the result of this SHL, and if it's a shift of a
7881 // constant amount, we can always perform a SHL in a smaller type.
7882 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007883 uint32_t BitWidth = Ty->getScalarSizeInBits();
7884 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007885 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007886 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007887 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007888 }
7889 break;
7890 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007891 // If this is a truncate of a logical shr, we can truncate it to a smaller
7892 // lshr iff we know that the bits we would otherwise be shifting in are
7893 // already zeros.
7894 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007895 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7896 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007897 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007898 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007899 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7900 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007901 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007902 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007903 }
7904 }
Chris Lattner46b96052006-11-29 07:18:39 +00007905 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007906 case Instruction::ZExt:
7907 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007908 case Instruction::Trunc:
7909 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007910 // can safely replace it. Note that replacing it does not reduce the number
7911 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007912 if (Opc == CastOpc)
7913 return true;
7914
7915 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007916 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007917 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007918 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007919 case Instruction::Select: {
7920 SelectInst *SI = cast<SelectInst>(I);
7921 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007922 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007923 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007924 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007925 }
Chris Lattner8114b712008-06-18 04:00:49 +00007926 case Instruction::PHI: {
7927 // We can change a phi if we can change all operands.
7928 PHINode *PN = cast<PHINode>(I);
7929 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7930 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007931 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007932 return false;
7933 return true;
7934 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007935 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007936 // TODO: Can handle more cases here.
7937 break;
7938 }
7939
7940 return false;
7941}
7942
7943/// EvaluateInDifferentType - Given an expression that
7944/// CanEvaluateInDifferentType returns true for, actually insert the code to
7945/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007946Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007947 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007948 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007949 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007950 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007951
7952 // Otherwise, it must be an instruction.
7953 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007954 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007955 unsigned Opc = I->getOpcode();
7956 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007957 case Instruction::Add:
7958 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007959 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007960 case Instruction::And:
7961 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007962 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007963 case Instruction::AShr:
7964 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007965 case Instruction::Shl:
7966 case Instruction::UDiv:
7967 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007968 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007969 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007970 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007971 break;
7972 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007973 case Instruction::Trunc:
7974 case Instruction::ZExt:
7975 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007976 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007977 // just return the source. There's no need to insert it because it is not
7978 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007979 if (I->getOperand(0)->getType() == Ty)
7980 return I->getOperand(0);
7981
Chris Lattner8114b712008-06-18 04:00:49 +00007982 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007983 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007984 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007985 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007986 case Instruction::Select: {
7987 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7988 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7989 Res = SelectInst::Create(I->getOperand(0), True, False);
7990 break;
7991 }
Chris Lattner8114b712008-06-18 04:00:49 +00007992 case Instruction::PHI: {
7993 PHINode *OPN = cast<PHINode>(I);
7994 PHINode *NPN = PHINode::Create(Ty);
7995 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7996 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7997 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7998 }
7999 Res = NPN;
8000 break;
8001 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008002 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008003 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008004 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008005 break;
8006 }
8007
Chris Lattner8114b712008-06-18 04:00:49 +00008008 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008009 return InsertNewInstBefore(Res, *I);
8010}
8011
Reid Spencer3da59db2006-11-27 01:05:10 +00008012/// @brief Implement the transforms common to all CastInst visitors.
8013Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008014 Value *Src = CI.getOperand(0);
8015
Dan Gohman23d9d272007-05-11 21:10:54 +00008016 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008017 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008018 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008019 if (Instruction::CastOps opc =
8020 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8021 // The first cast (CSrc) is eliminable so we need to fix up or replace
8022 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008023 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008024 }
8025 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008026
Reid Spencer3da59db2006-11-27 01:05:10 +00008027 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008028 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8029 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8030 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008031
8032 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008033 if (isa<PHINode>(Src))
8034 if (Instruction *NV = FoldOpIntoPhi(CI))
8035 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008036
Reid Spencer3da59db2006-11-27 01:05:10 +00008037 return 0;
8038}
8039
Chris Lattner46cd5a12009-01-09 05:44:56 +00008040/// FindElementAtOffset - Given a type and a constant offset, determine whether
8041/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008042/// the specified offset. If so, fill them into NewIndices and return the
8043/// resultant element type, otherwise return null.
8044static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8045 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008046 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008047 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008048 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008049 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008050
8051 // Start with the index over the outer type. Note that the type size
8052 // might be zero (even if the offset isn't zero) if the indexed type
8053 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008054 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008055 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008056 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008057 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008058 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008059
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008060 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008061 if (Offset < 0) {
8062 --FirstIdx;
8063 Offset += TySize;
8064 assert(Offset >= 0);
8065 }
8066 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8067 }
8068
Owen Andersoneed707b2009-07-24 23:12:02 +00008069 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008070
8071 // Index into the types. If we fail, set OrigBase to null.
8072 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008073 // Indexing into tail padding between struct/array elements.
8074 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008075 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008076
Chris Lattner46cd5a12009-01-09 05:44:56 +00008077 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8078 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008079 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8080 "Offset must stay within the indexed type");
8081
Chris Lattner46cd5a12009-01-09 05:44:56 +00008082 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008083 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008084
8085 Offset -= SL->getElementOffset(Elt);
8086 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008087 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008088 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008089 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008090 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008091 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008092 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008093 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008094 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008095 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008096 }
8097 }
8098
Chris Lattner3914f722009-01-24 01:00:13 +00008099 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008100}
8101
Chris Lattnerd3e28342007-04-27 17:44:50 +00008102/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8103Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8104 Value *Src = CI.getOperand(0);
8105
Chris Lattnerd3e28342007-04-27 17:44:50 +00008106 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008107 // If casting the result of a getelementptr instruction with no offset, turn
8108 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008109 if (GEP->hasAllZeroIndices()) {
8110 // Changing the cast operand is usually not a good idea but it is safe
8111 // here because the pointer operand is being replaced with another
8112 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008113 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008114 CI.setOperand(0, GEP->getOperand(0));
8115 return &CI;
8116 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008117
8118 // If the GEP has a single use, and the base pointer is a bitcast, and the
8119 // GEP computes a constant offset, see if we can convert these three
8120 // instructions into fewer. This typically happens with unions and other
8121 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008122 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008123 if (GEP->hasAllConstantIndices()) {
8124 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008125 ConstantInt *OffsetV =
8126 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008127 int64_t Offset = OffsetV->getSExtValue();
8128
8129 // Get the base pointer input of the bitcast, and the type it points to.
8130 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8131 const Type *GEPIdxTy =
8132 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008133 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008134 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008135 // If we were able to index down into an element, create the GEP
8136 // and bitcast the result. This eliminates one bitcast, potentially
8137 // two.
8138 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8139 NewIndices.begin(),
8140 NewIndices.end(), "");
8141 InsertNewInstBefore(NGEP, CI);
8142 NGEP->takeName(GEP);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008143 if (cast<GEPOperator>(GEP)->isInBounds())
8144 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008145
Chris Lattner46cd5a12009-01-09 05:44:56 +00008146 if (isa<BitCastInst>(CI))
8147 return new BitCastInst(NGEP, CI.getType());
8148 assert(isa<PtrToIntInst>(CI));
8149 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008150 }
8151 }
8152 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008153 }
8154
8155 return commonCastTransforms(CI);
8156}
8157
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008158/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8159/// type like i42. We don't want to introduce operations on random non-legal
8160/// integer types where they don't already exist in the code. In the future,
8161/// we should consider making this based off target-data, so that 32-bit targets
8162/// won't get i64 operations etc.
8163static bool isSafeIntegerType(const Type *Ty) {
8164 switch (Ty->getPrimitiveSizeInBits()) {
8165 case 8:
8166 case 16:
8167 case 32:
8168 case 64:
8169 return true;
8170 default:
8171 return false;
8172 }
8173}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008174
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008175/// commonIntCastTransforms - This function implements the common transforms
8176/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008177Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8178 if (Instruction *Result = commonCastTransforms(CI))
8179 return Result;
8180
8181 Value *Src = CI.getOperand(0);
8182 const Type *SrcTy = Src->getType();
8183 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008184 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8185 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008186
Reid Spencer3da59db2006-11-27 01:05:10 +00008187 // See if we can simplify any instructions used by the LHS whose sole
8188 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008189 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008190 return &CI;
8191
8192 // If the source isn't an instruction or has more than one use then we
8193 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008194 Instruction *SrcI = dyn_cast<Instruction>(Src);
8195 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008196 return 0;
8197
Chris Lattnerc739cd62007-03-03 05:27:34 +00008198 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008199 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008200 // Only do this if the dest type is a simple type, don't convert the
8201 // expression tree to something weird like i93 unless the source is also
8202 // strange.
8203 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008204 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8205 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008206 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008207 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008208 // eliminates the cast, so it is always a win. If this is a zero-extension,
8209 // we need to do an AND to maintain the clear top-part of the computation,
8210 // so we require that the input have eliminated at least one cast. If this
8211 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008212 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008213 bool DoXForm = false;
8214 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008215 switch (CI.getOpcode()) {
8216 default:
8217 // All the others use floating point so we shouldn't actually
8218 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008219 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008220 case Instruction::Trunc:
8221 DoXForm = true;
8222 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008223 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008224 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008225 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008226 // If it's unnecessary to issue an AND to clear the high bits, it's
8227 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008228 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008229 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8230 if (MaskedValueIsZero(TryRes, Mask))
8231 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008232
8233 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008234 if (TryI->use_empty())
8235 EraseInstFromFunction(*TryI);
8236 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008237 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008238 }
Evan Chengf35fd542009-01-15 17:01:23 +00008239 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008240 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008241 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008242 // If we do not have to emit the truncate + sext pair, then it's always
8243 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008244 //
8245 // It's not safe to eliminate the trunc + sext pair if one of the
8246 // eliminated cast is a truncate. e.g.
8247 // t2 = trunc i32 t1 to i16
8248 // t3 = sext i16 t2 to i32
8249 // !=
8250 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008251 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008252 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8253 if (NumSignBits > (DestBitSize - SrcBitSize))
8254 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008255
8256 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008257 if (TryI->use_empty())
8258 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008259 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008260 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008261 }
Evan Chengf35fd542009-01-15 17:01:23 +00008262 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008263
8264 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008265 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8266 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008267 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8268 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008269 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008270 // Just replace this cast with the result.
8271 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008272
Reid Spencer3da59db2006-11-27 01:05:10 +00008273 assert(Res->getType() == DestTy);
8274 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008275 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008277 // Just replace this cast with the result.
8278 return ReplaceInstUsesWith(CI, Res);
8279 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008280 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008281
8282 // If the high bits are already zero, just replace this cast with the
8283 // result.
8284 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8285 if (MaskedValueIsZero(Res, Mask))
8286 return ReplaceInstUsesWith(CI, Res);
8287
8288 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008289 Constant *C = ConstantInt::get(*Context,
8290 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008291 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008292 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008293 case Instruction::SExt: {
8294 // If the high bits are already filled with sign bit, just replace this
8295 // cast with the result.
8296 unsigned NumSignBits = ComputeNumSignBits(Res);
8297 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008298 return ReplaceInstUsesWith(CI, Res);
8299
Reid Spencer3da59db2006-11-27 01:05:10 +00008300 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008301 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008302 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8303 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008304 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008305 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008306 }
8307 }
8308
8309 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8310 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8311
8312 switch (SrcI->getOpcode()) {
8313 case Instruction::Add:
8314 case Instruction::Mul:
8315 case Instruction::And:
8316 case Instruction::Or:
8317 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008318 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008319 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8320 // Don't insert two casts unless at least one can be eliminated.
8321 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008322 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008323 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8324 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008325 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008326 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008327 }
8328 }
8329
8330 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8331 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8332 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008333 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008334 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008335 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008336 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008337 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008338 }
8339 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008340
Eli Friedman65445c52009-07-13 21:45:57 +00008341 case Instruction::Shl: {
8342 // Canonicalize trunc inside shl, if we can.
8343 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8344 if (CI && DestBitSize < SrcBitSize &&
8345 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8346 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8347 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008348 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008349 }
8350 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008351 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008352 }
8353 return 0;
8354}
8355
Chris Lattner8a9f5712007-04-11 06:57:46 +00008356Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008357 if (Instruction *Result = commonIntCastTransforms(CI))
8358 return Result;
8359
8360 Value *Src = CI.getOperand(0);
8361 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008362 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8363 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008364
8365 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008366 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008367 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008368 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Andersona7235ea2009-07-31 20:28:14 +00008369 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008370 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008371 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008372
Chris Lattner4f9797d2009-03-24 18:15:30 +00008373 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8374 ConstantInt *ShAmtV = 0;
8375 Value *ShiftOp = 0;
8376 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008377 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008378 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8379
8380 // Get a mask for the bits shifting in.
8381 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8382 if (MaskedValueIsZero(ShiftOp, Mask)) {
8383 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008384 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008385
8386 // Okay, we can shrink this. Truncate the input, then return a new
8387 // shift.
8388 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008389 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008390 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008391 }
8392 }
8393
8394 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008395}
8396
Evan Chengb98a10e2008-03-24 00:21:34 +00008397/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8398/// in order to eliminate the icmp.
8399Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8400 bool DoXform) {
8401 // If we are just checking for a icmp eq of a single bit and zext'ing it
8402 // to an integer, then shift the bit to the appropriate place and then
8403 // cast to integer to avoid the comparison.
8404 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8405 const APInt &Op1CV = Op1C->getValue();
8406
8407 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8408 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8409 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8410 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8411 if (!DoXform) return ICI;
8412
8413 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008414 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008415 In->getType()->getScalarSizeInBits()-1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008416 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chengb98a10e2008-03-24 00:21:34 +00008417 In->getName()+".lobit"),
8418 CI);
8419 if (In->getType() != CI.getType())
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008420 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chengb98a10e2008-03-24 00:21:34 +00008421 false/*ZExt*/, "tmp", &CI);
8422
8423 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008424 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008425 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chengb98a10e2008-03-24 00:21:34 +00008426 In->getName()+".not"),
8427 CI);
8428 }
8429
8430 return ReplaceInstUsesWith(CI, In);
8431 }
8432
8433
8434
8435 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8436 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8437 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8438 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8439 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8440 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8441 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8442 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8443 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8444 // This only works for EQ and NE
8445 ICI->isEquality()) {
8446 // If Op1C some other power of two, convert:
8447 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8448 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8449 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8450 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8451
8452 APInt KnownZeroMask(~KnownZero);
8453 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8454 if (!DoXform) return ICI;
8455
8456 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8457 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8458 // (X&4) == 2 --> false
8459 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008460 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008461 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008462 return ReplaceInstUsesWith(CI, Res);
8463 }
8464
8465 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8466 Value *In = ICI->getOperand(0);
8467 if (ShiftAmt) {
8468 // Perform a logical shr by shiftamt.
8469 // Insert the shift to put the result in the low bit.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008470 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Andersoneed707b2009-07-24 23:12:02 +00008471 ConstantInt::get(In->getType(), ShiftAmt),
Evan Chengb98a10e2008-03-24 00:21:34 +00008472 In->getName()+".lobit"), CI);
8473 }
8474
8475 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008476 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008477 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008478 InsertNewInstBefore(cast<Instruction>(In), CI);
8479 }
8480
8481 if (CI.getType() == In->getType())
8482 return ReplaceInstUsesWith(CI, In);
8483 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008484 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008485 }
8486 }
8487 }
8488
8489 return 0;
8490}
8491
Chris Lattner8a9f5712007-04-11 06:57:46 +00008492Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008493 // If one of the common conversion will work ..
8494 if (Instruction *Result = commonIntCastTransforms(CI))
8495 return Result;
8496
8497 Value *Src = CI.getOperand(0);
8498
Chris Lattnera84f47c2009-02-17 20:47:23 +00008499 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8500 // types and if the sizes are just right we can convert this into a logical
8501 // 'and' which will be much cheaper than the pair of casts.
8502 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8503 // Get the sizes of the types involved. We know that the intermediate type
8504 // will be smaller than A or C, but don't know the relation between A and C.
8505 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008506 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8507 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8508 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008509 // If we're actually extending zero bits, then if
8510 // SrcSize < DstSize: zext(a & mask)
8511 // SrcSize == DstSize: a & mask
8512 // SrcSize > DstSize: trunc(a) & mask
8513 if (SrcSize < DstSize) {
8514 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008515 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnera84f47c2009-02-17 20:47:23 +00008516 Instruction *And =
8517 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8518 InsertNewInstBefore(And, CI);
8519 return new ZExtInst(And, CI.getType());
8520 } else if (SrcSize == DstSize) {
8521 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008522 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008523 AndValue));
Chris Lattnera84f47c2009-02-17 20:47:23 +00008524 } else if (SrcSize > DstSize) {
8525 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8526 InsertNewInstBefore(Trunc, CI);
8527 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008528 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008529 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008530 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008531 }
8532 }
8533
Evan Chengb98a10e2008-03-24 00:21:34 +00008534 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8535 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008536
Evan Chengb98a10e2008-03-24 00:21:34 +00008537 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8538 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8539 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8540 // of the (zext icmp) will be transformed.
8541 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8542 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8543 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8544 (transformZExtICmp(LHS, CI, false) ||
8545 transformZExtICmp(RHS, CI, false))) {
8546 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8547 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008548 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008549 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008550 }
8551
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008552 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008553 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8554 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8555 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8556 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008557 if (TI0->getType() == CI.getType())
8558 return
8559 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008560 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008561 }
8562
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008563 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8564 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8565 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8566 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8567 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8568 And->getOperand(1) == C)
8569 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8570 Value *TI0 = TI->getOperand(0);
8571 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008572 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008573 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8574 InsertNewInstBefore(NewAnd, *And);
8575 return BinaryOperator::CreateXor(NewAnd, ZC);
8576 }
8577 }
8578
Reid Spencer3da59db2006-11-27 01:05:10 +00008579 return 0;
8580}
8581
Chris Lattner8a9f5712007-04-11 06:57:46 +00008582Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008583 if (Instruction *I = commonIntCastTransforms(CI))
8584 return I;
8585
Chris Lattner8a9f5712007-04-11 06:57:46 +00008586 Value *Src = CI.getOperand(0);
8587
Dan Gohman1975d032008-10-30 20:40:10 +00008588 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008589 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008590 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008591 Constant::getAllOnesValue(CI.getType()),
8592 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008593
8594 // See if the value being truncated is already sign extended. If so, just
8595 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008596 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008597 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008598 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8599 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8600 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008601 unsigned NumSignBits = ComputeNumSignBits(Op);
8602
8603 if (OpBits == DestBits) {
8604 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8605 // bits, it is already ready.
8606 if (NumSignBits > DestBits-MidBits)
8607 return ReplaceInstUsesWith(CI, Op);
8608 } else if (OpBits < DestBits) {
8609 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8610 // bits, just sext from i32.
8611 if (NumSignBits > OpBits-MidBits)
8612 return new SExtInst(Op, CI.getType(), "tmp");
8613 } else {
8614 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8615 // bits, just truncate to i32.
8616 if (NumSignBits > OpBits-MidBits)
8617 return new TruncInst(Op, CI.getType(), "tmp");
8618 }
8619 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008620
8621 // If the input is a shl/ashr pair of a same constant, then this is a sign
8622 // extension from a smaller value. If we could trust arbitrary bitwidth
8623 // integers, we could turn this into a truncate to the smaller bit and then
8624 // use a sext for the whole extension. Since we don't, look deeper and check
8625 // for a truncate. If the source and dest are the same type, eliminate the
8626 // trunc and extend and just do shifts. For example, turn:
8627 // %a = trunc i32 %i to i8
8628 // %b = shl i8 %a, 6
8629 // %c = ashr i8 %b, 6
8630 // %d = sext i8 %c to i32
8631 // into:
8632 // %a = shl i32 %i, 30
8633 // %d = ashr i32 %a, 30
8634 Value *A = 0;
8635 ConstantInt *BA = 0, *CA = 0;
8636 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008637 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008638 BA == CA && isa<TruncInst>(A)) {
8639 Value *I = cast<TruncInst>(A)->getOperand(0);
8640 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008641 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8642 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008643 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008644 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattner46bbad22008-08-06 07:35:52 +00008645 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8646 CI.getName()), CI);
8647 return BinaryOperator::CreateAShr(I, ShAmtV);
8648 }
8649 }
8650
Chris Lattnerba417832007-04-11 06:12:58 +00008651 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008652}
8653
Chris Lattnerb7530652008-01-27 05:29:54 +00008654/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8655/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008656static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008657 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008658 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008659 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008660 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8661 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008662 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008663 return 0;
8664}
8665
8666/// LookThroughFPExtensions - If this is an fp extension instruction, look
8667/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008668static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008669 if (Instruction *I = dyn_cast<Instruction>(V))
8670 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008671 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008672
8673 // If this value is a constant, return the constant in the smallest FP type
8674 // that can accurately represent it. This allows us to turn
8675 // (float)((double)X+2.0) into x+2.0f.
8676 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008677 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008678 return V; // No constant folding of this.
8679 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008680 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008681 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008682 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008683 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008684 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008685 return V;
8686 // Don't try to shrink to various long double types.
8687 }
8688
8689 return V;
8690}
8691
8692Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8693 if (Instruction *I = commonCastTransforms(CI))
8694 return I;
8695
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008696 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008697 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008698 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008699 // many builtins (sqrt, etc).
8700 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8701 if (OpI && OpI->hasOneUse()) {
8702 switch (OpI->getOpcode()) {
8703 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008704 case Instruction::FAdd:
8705 case Instruction::FSub:
8706 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008707 case Instruction::FDiv:
8708 case Instruction::FRem:
8709 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008710 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8711 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008712 if (LHSTrunc->getType() != SrcTy &&
8713 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008714 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008715 // If the source types were both smaller than the destination type of
8716 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008717 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8718 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008719 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8720 CI.getType(), CI);
8721 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8722 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008723 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008724 }
8725 }
8726 break;
8727 }
8728 }
8729 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008730}
8731
8732Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8733 return commonCastTransforms(CI);
8734}
8735
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008736Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008737 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8738 if (OpI == 0)
8739 return commonCastTransforms(FI);
8740
8741 // fptoui(uitofp(X)) --> X
8742 // fptoui(sitofp(X)) --> X
8743 // This is safe if the intermediate type has enough bits in its mantissa to
8744 // accurately represent all values of X. For example, do not do this with
8745 // i64->float->i64. This is also safe for sitofp case, because any negative
8746 // 'X' value would cause an undefined result for the fptoui.
8747 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8748 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008749 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008750 OpI->getType()->getFPMantissaWidth())
8751 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008752
8753 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008754}
8755
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008756Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008757 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8758 if (OpI == 0)
8759 return commonCastTransforms(FI);
8760
8761 // fptosi(sitofp(X)) --> X
8762 // fptosi(uitofp(X)) --> X
8763 // This is safe if the intermediate type has enough bits in its mantissa to
8764 // accurately represent all values of X. For example, do not do this with
8765 // i64->float->i64. This is also safe for sitofp case, because any negative
8766 // 'X' value would cause an undefined result for the fptoui.
8767 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8768 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008769 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008770 OpI->getType()->getFPMantissaWidth())
8771 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008772
8773 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008774}
8775
8776Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8777 return commonCastTransforms(CI);
8778}
8779
8780Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8781 return commonCastTransforms(CI);
8782}
8783
Chris Lattnera0e69692009-03-24 18:35:40 +00008784Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8785 // If the destination integer type is smaller than the intptr_t type for
8786 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8787 // trunc to be exposed to other transforms. Don't do this for extending
8788 // ptrtoint's, because we don't know if the target sign or zero extends its
8789 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008790 if (TD &&
8791 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008792 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008793 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008794 "tmp"), CI);
8795 return new TruncInst(P, CI.getType());
8796 }
8797
Chris Lattnerd3e28342007-04-27 17:44:50 +00008798 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008799}
8800
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008801Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008802 // If the source integer type is larger than the intptr_t type for
8803 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8804 // allows the trunc to be exposed to other transforms. Don't do this for
8805 // extending inttoptr's, because we don't know if the target sign or zero
8806 // extends to pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008807 if (TD &&
8808 CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008809 TD->getPointerSizeInBits()) {
8810 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
Owen Anderson1d0be152009-08-13 21:58:54 +00008811 TD->getIntPtrType(CI.getContext()),
Chris Lattnera0e69692009-03-24 18:35:40 +00008812 "tmp"), CI);
8813 return new IntToPtrInst(P, CI.getType());
8814 }
8815
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008816 if (Instruction *I = commonCastTransforms(CI))
8817 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008818
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008819 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008820}
8821
Chris Lattnerd3e28342007-04-27 17:44:50 +00008822Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008823 // If the operands are integer typed then apply the integer transforms,
8824 // otherwise just apply the common ones.
8825 Value *Src = CI.getOperand(0);
8826 const Type *SrcTy = Src->getType();
8827 const Type *DestTy = CI.getType();
8828
Eli Friedman7e25d452009-07-13 20:53:00 +00008829 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008830 if (Instruction *I = commonPointerCastTransforms(CI))
8831 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008832 } else {
8833 if (Instruction *Result = commonCastTransforms(CI))
8834 return Result;
8835 }
8836
8837
8838 // Get rid of casts from one type to the same type. These are useless and can
8839 // be replaced by the operand.
8840 if (DestTy == Src->getType())
8841 return ReplaceInstUsesWith(CI, Src);
8842
Reid Spencer3da59db2006-11-27 01:05:10 +00008843 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008844 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8845 const Type *DstElTy = DstPTy->getElementType();
8846 const Type *SrcElTy = SrcPTy->getElementType();
8847
Nate Begeman83ad90a2008-03-31 00:22:16 +00008848 // If the address spaces don't match, don't eliminate the bitcast, which is
8849 // required for changing types.
8850 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8851 return 0;
8852
Chris Lattnerd3e28342007-04-27 17:44:50 +00008853 // If we are casting a malloc or alloca to a pointer to a type of the same
8854 // size, rewrite the allocation instruction to allocate the "right" type.
8855 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8856 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8857 return V;
8858
Chris Lattnerd717c182007-05-05 22:32:24 +00008859 // If the source and destination are pointers, and this cast is equivalent
8860 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008861 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008862 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008863 unsigned NumZeros = 0;
8864 while (SrcElTy != DstElTy &&
8865 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8866 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8867 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8868 ++NumZeros;
8869 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008870
Chris Lattnerd3e28342007-04-27 17:44:50 +00008871 // If we found a path from the src to dest, create the getelementptr now.
8872 if (SrcElTy == DstElTy) {
8873 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008874 Instruction *GEP = GetElementPtrInst::Create(Src,
8875 Idxs.begin(), Idxs.end(), "",
8876 ((Instruction*) NULL));
8877 cast<GEPOperator>(GEP)->setIsInBounds(true);
8878 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008879 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008880 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008881
Eli Friedman2451a642009-07-18 23:06:53 +00008882 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8883 if (DestVTy->getNumElements() == 1) {
8884 if (!isa<VectorType>(SrcTy)) {
8885 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8886 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008887 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00008888 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008889 }
8890 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8891 }
8892 }
8893
8894 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8895 if (SrcVTy->getNumElements() == 1) {
8896 if (!isa<VectorType>(DestTy)) {
8897 Instruction *Elem =
Owen Anderson1d0be152009-08-13 21:58:54 +00008898 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008899 InsertNewInstBefore(Elem, CI);
8900 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8901 }
8902 }
8903 }
8904
Reid Spencer3da59db2006-11-27 01:05:10 +00008905 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8906 if (SVI->hasOneUse()) {
8907 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8908 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008909 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008910 cast<VectorType>(DestTy)->getNumElements() ==
8911 SVI->getType()->getNumElements() &&
8912 SVI->getType()->getNumElements() ==
8913 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008914 CastInst *Tmp;
8915 // If either of the operands is a cast from CI.getType(), then
8916 // evaluating the shuffle in the casted destination's type will allow
8917 // us to eliminate at least one cast.
8918 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8919 Tmp->getOperand(0)->getType() == DestTy) ||
8920 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8921 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008922 Value *LHS = InsertCastBefore(Instruction::BitCast,
8923 SVI->getOperand(0), DestTy, CI);
8924 Value *RHS = InsertCastBefore(Instruction::BitCast,
8925 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008926 // Return a new shuffle vector. Use the same element ID's, as we
8927 // know the vector types match #elts.
8928 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008929 }
8930 }
8931 }
8932 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008933 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008934}
8935
Chris Lattnere576b912004-04-09 23:46:01 +00008936/// GetSelectFoldableOperands - We want to turn code that looks like this:
8937/// %C = or %A, %B
8938/// %D = select %cond, %C, %A
8939/// into:
8940/// %C = select %cond, %B, 0
8941/// %D = or %A, %C
8942///
8943/// Assuming that the specified instruction is an operand to the select, return
8944/// a bitmask indicating which operands of this instruction are foldable if they
8945/// equal the other incoming value of the select.
8946///
8947static unsigned GetSelectFoldableOperands(Instruction *I) {
8948 switch (I->getOpcode()) {
8949 case Instruction::Add:
8950 case Instruction::Mul:
8951 case Instruction::And:
8952 case Instruction::Or:
8953 case Instruction::Xor:
8954 return 3; // Can fold through either operand.
8955 case Instruction::Sub: // Can only fold on the amount subtracted.
8956 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008957 case Instruction::LShr:
8958 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008959 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008960 default:
8961 return 0; // Cannot fold
8962 }
8963}
8964
8965/// GetSelectFoldableConstant - For the same transformation as the previous
8966/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008967static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008968 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008969 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008970 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008971 case Instruction::Add:
8972 case Instruction::Sub:
8973 case Instruction::Or:
8974 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008975 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008976 case Instruction::LShr:
8977 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008978 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008979 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008980 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008981 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008982 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008983 }
8984}
8985
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008986/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8987/// have the same opcode and only one use each. Try to simplify this.
8988Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8989 Instruction *FI) {
8990 if (TI->getNumOperands() == 1) {
8991 // If this is a non-volatile load or a cast from the same type,
8992 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008993 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008994 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8995 return 0;
8996 } else {
8997 return 0; // unknown unary op.
8998 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008999
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009000 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009001 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009002 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009003 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009004 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009005 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009006 }
9007
Reid Spencer832254e2007-02-02 02:16:23 +00009008 // Only handle binary operators here.
9009 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009010 return 0;
9011
9012 // Figure out if the operations have any operands in common.
9013 Value *MatchOp, *OtherOpT, *OtherOpF;
9014 bool MatchIsOpZero;
9015 if (TI->getOperand(0) == FI->getOperand(0)) {
9016 MatchOp = TI->getOperand(0);
9017 OtherOpT = TI->getOperand(1);
9018 OtherOpF = FI->getOperand(1);
9019 MatchIsOpZero = true;
9020 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9021 MatchOp = TI->getOperand(1);
9022 OtherOpT = TI->getOperand(0);
9023 OtherOpF = FI->getOperand(0);
9024 MatchIsOpZero = false;
9025 } else if (!TI->isCommutative()) {
9026 return 0;
9027 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9028 MatchOp = TI->getOperand(0);
9029 OtherOpT = TI->getOperand(1);
9030 OtherOpF = FI->getOperand(0);
9031 MatchIsOpZero = true;
9032 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9033 MatchOp = TI->getOperand(1);
9034 OtherOpT = TI->getOperand(0);
9035 OtherOpF = FI->getOperand(1);
9036 MatchIsOpZero = true;
9037 } else {
9038 return 0;
9039 }
9040
9041 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009042 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9043 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009044 InsertNewInstBefore(NewSI, SI);
9045
9046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9047 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009048 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009049 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009050 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009051 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009052 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009053 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009054}
9055
Evan Chengde621922009-03-31 20:42:45 +00009056static bool isSelect01(Constant *C1, Constant *C2) {
9057 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9058 if (!C1I)
9059 return false;
9060 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9061 if (!C2I)
9062 return false;
9063 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9064}
9065
9066/// FoldSelectIntoOp - Try fold the select into one of the operands to
9067/// facilitate further optimization.
9068Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9069 Value *FalseVal) {
9070 // See the comment above GetSelectFoldableOperands for a description of the
9071 // transformation we are doing here.
9072 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9073 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9074 !isa<Constant>(FalseVal)) {
9075 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9076 unsigned OpToFold = 0;
9077 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9078 OpToFold = 1;
9079 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9080 OpToFold = 2;
9081 }
9082
9083 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009084 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009085 Value *OOp = TVI->getOperand(2-OpToFold);
9086 // Avoid creating select between 2 constants unless it's selecting
9087 // between 0 and 1.
9088 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9089 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9090 InsertNewInstBefore(NewSel, SI);
9091 NewSel->takeName(TVI);
9092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9093 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009094 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009095 }
9096 }
9097 }
9098 }
9099 }
9100
9101 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9102 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9103 !isa<Constant>(TrueVal)) {
9104 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9105 unsigned OpToFold = 0;
9106 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9107 OpToFold = 1;
9108 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9109 OpToFold = 2;
9110 }
9111
9112 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009113 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009114 Value *OOp = FVI->getOperand(2-OpToFold);
9115 // Avoid creating select between 2 constants unless it's selecting
9116 // between 0 and 1.
9117 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9118 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9119 InsertNewInstBefore(NewSel, SI);
9120 NewSel->takeName(FVI);
9121 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9122 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009123 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009124 }
9125 }
9126 }
9127 }
9128 }
9129
9130 return 0;
9131}
9132
Dan Gohman81b28ce2008-09-16 18:46:06 +00009133/// visitSelectInstWithICmp - Visit a SelectInst that has an
9134/// ICmpInst as its first operand.
9135///
9136Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9137 ICmpInst *ICI) {
9138 bool Changed = false;
9139 ICmpInst::Predicate Pred = ICI->getPredicate();
9140 Value *CmpLHS = ICI->getOperand(0);
9141 Value *CmpRHS = ICI->getOperand(1);
9142 Value *TrueVal = SI.getTrueValue();
9143 Value *FalseVal = SI.getFalseValue();
9144
9145 // Check cases where the comparison is with a constant that
9146 // can be adjusted to fit the min/max idiom. We may edit ICI in
9147 // place here, so make sure the select is the only user.
9148 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009149 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009150 switch (Pred) {
9151 default: break;
9152 case ICmpInst::ICMP_ULT:
9153 case ICmpInst::ICMP_SLT: {
9154 // X < MIN ? T : F --> F
9155 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9156 return ReplaceInstUsesWith(SI, FalseVal);
9157 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009158 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009159 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9160 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9161 Pred = ICmpInst::getSwappedPredicate(Pred);
9162 CmpRHS = AdjustedRHS;
9163 std::swap(FalseVal, TrueVal);
9164 ICI->setPredicate(Pred);
9165 ICI->setOperand(1, CmpRHS);
9166 SI.setOperand(1, TrueVal);
9167 SI.setOperand(2, FalseVal);
9168 Changed = true;
9169 }
9170 break;
9171 }
9172 case ICmpInst::ICMP_UGT:
9173 case ICmpInst::ICMP_SGT: {
9174 // X > MAX ? T : F --> F
9175 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9176 return ReplaceInstUsesWith(SI, FalseVal);
9177 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009178 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009179 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9180 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9181 Pred = ICmpInst::getSwappedPredicate(Pred);
9182 CmpRHS = AdjustedRHS;
9183 std::swap(FalseVal, TrueVal);
9184 ICI->setPredicate(Pred);
9185 ICI->setOperand(1, CmpRHS);
9186 SI.setOperand(1, TrueVal);
9187 SI.setOperand(2, FalseVal);
9188 Changed = true;
9189 }
9190 break;
9191 }
9192 }
9193
Dan Gohman1975d032008-10-30 20:40:10 +00009194 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9195 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009196 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009197 if (match(TrueVal, m_ConstantInt<-1>()) &&
9198 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009199 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009200 else if (match(TrueVal, m_ConstantInt<0>()) &&
9201 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009202 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9203
Dan Gohman1975d032008-10-30 20:40:10 +00009204 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9205 // If we are just checking for a icmp eq of a single bit and zext'ing it
9206 // to an integer, then shift the bit to the appropriate place and then
9207 // cast to integer to avoid the comparison.
9208 const APInt &Op1CV = CI->getValue();
9209
9210 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9211 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9212 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009213 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009214 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009215 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009216 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009217 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009218 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009219 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009220 if (In->getType() != SI.getType())
9221 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009222 true/*SExt*/, "tmp", ICI);
9223
9224 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009225 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009226 In->getName()+".not"), *ICI);
9227
9228 return ReplaceInstUsesWith(SI, In);
9229 }
9230 }
9231 }
9232
Dan Gohman81b28ce2008-09-16 18:46:06 +00009233 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9234 // Transform (X == Y) ? X : Y -> Y
9235 if (Pred == ICmpInst::ICMP_EQ)
9236 return ReplaceInstUsesWith(SI, FalseVal);
9237 // Transform (X != Y) ? X : Y -> X
9238 if (Pred == ICmpInst::ICMP_NE)
9239 return ReplaceInstUsesWith(SI, TrueVal);
9240 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9241
9242 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9243 // Transform (X == Y) ? Y : X -> X
9244 if (Pred == ICmpInst::ICMP_EQ)
9245 return ReplaceInstUsesWith(SI, FalseVal);
9246 // Transform (X != Y) ? Y : X -> Y
9247 if (Pred == ICmpInst::ICMP_NE)
9248 return ReplaceInstUsesWith(SI, TrueVal);
9249 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9250 }
9251
9252 /// NOTE: if we wanted to, this is where to detect integer ABS
9253
9254 return Changed ? &SI : 0;
9255}
9256
Chris Lattner3d69f462004-03-12 05:52:32 +00009257Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009258 Value *CondVal = SI.getCondition();
9259 Value *TrueVal = SI.getTrueValue();
9260 Value *FalseVal = SI.getFalseValue();
9261
9262 // select true, X, Y -> X
9263 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009264 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009265 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009266
9267 // select C, X, X -> X
9268 if (TrueVal == FalseVal)
9269 return ReplaceInstUsesWith(SI, TrueVal);
9270
Chris Lattnere87597f2004-10-16 18:11:37 +00009271 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9272 return ReplaceInstUsesWith(SI, FalseVal);
9273 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9274 return ReplaceInstUsesWith(SI, TrueVal);
9275 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9276 if (isa<Constant>(TrueVal))
9277 return ReplaceInstUsesWith(SI, TrueVal);
9278 else
9279 return ReplaceInstUsesWith(SI, FalseVal);
9280 }
9281
Owen Anderson1d0be152009-08-13 21:58:54 +00009282 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009283 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009284 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009285 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009286 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009287 } else {
9288 // Change: A = select B, false, C --> A = and !B, C
9289 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009290 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009291 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009292 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009293 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009294 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009295 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009296 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009297 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009298 } else {
9299 // Change: A = select B, C, true --> A = or !B, C
9300 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009301 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009302 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009303 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009304 }
9305 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009306
9307 // select a, b, a -> a&b
9308 // select a, a, b -> a|b
9309 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009310 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009311 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009312 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009313 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009314
Chris Lattner2eefe512004-04-09 19:05:30 +00009315 // Selecting between two integer constants?
9316 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9317 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009318 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009319 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009320 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009321 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009322 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009323 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009324 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009325 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009326 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009327 }
Chris Lattner457dd822004-06-09 07:59:58 +00009328
Reid Spencere4d87aa2006-12-23 06:05:41 +00009329 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009330 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009331 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009332 // non-constant value, eliminate this whole mess. This corresponds to
9333 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009334 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009335 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009336 cast<Constant>(IC->getOperand(1))->isNullValue())
9337 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9338 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009339 isa<ConstantInt>(ICA->getOperand(1)) &&
9340 (ICA->getOperand(1) == TrueValC ||
9341 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009342 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9343 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009344 // know whether we have a icmp_ne or icmp_eq and whether the
9345 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009346 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009347 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009348 Value *V = ICA;
9349 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009350 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009351 Instruction::Xor, V, ICA->getOperand(1)), SI);
9352 return ReplaceInstUsesWith(SI, V);
9353 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009354 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009355 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009356
9357 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009358 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9359 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009360 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009361 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9362 // This is not safe in general for floating point:
9363 // consider X== -0, Y== +0.
9364 // It becomes safe if either operand is a nonzero constant.
9365 ConstantFP *CFPt, *CFPf;
9366 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9367 !CFPt->getValueAPF().isZero()) ||
9368 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9369 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009370 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009371 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009372 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009373 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009374 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009375 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009376
Reid Spencere4d87aa2006-12-23 06:05:41 +00009377 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009378 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009379 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9380 // This is not safe in general for floating point:
9381 // consider X== -0, Y== +0.
9382 // It becomes safe if either operand is a nonzero constant.
9383 ConstantFP *CFPt, *CFPf;
9384 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9385 !CFPt->getValueAPF().isZero()) ||
9386 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9387 !CFPf->getValueAPF().isZero()))
9388 return ReplaceInstUsesWith(SI, FalseVal);
9389 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009390 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009391 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9392 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009393 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009394 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009395 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009396 }
9397
9398 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009399 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9400 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9401 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009402
Chris Lattner87875da2005-01-13 22:52:24 +00009403 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9404 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9405 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009406 Instruction *AddOp = 0, *SubOp = 0;
9407
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009408 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9409 if (TI->getOpcode() == FI->getOpcode())
9410 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9411 return IV;
9412
9413 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9414 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009415 if ((TI->getOpcode() == Instruction::Sub &&
9416 FI->getOpcode() == Instruction::Add) ||
9417 (TI->getOpcode() == Instruction::FSub &&
9418 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009419 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009420 } else if ((FI->getOpcode() == Instruction::Sub &&
9421 TI->getOpcode() == Instruction::Add) ||
9422 (FI->getOpcode() == Instruction::FSub &&
9423 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009424 AddOp = TI; SubOp = FI;
9425 }
9426
9427 if (AddOp) {
9428 Value *OtherAddOp = 0;
9429 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9430 OtherAddOp = AddOp->getOperand(1);
9431 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9432 OtherAddOp = AddOp->getOperand(0);
9433 }
9434
9435 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009436 // So at this point we know we have (Y -> OtherAddOp):
9437 // select C, (add X, Y), (sub X, Z)
9438 Value *NegVal; // Compute -Z
9439 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009440 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009441 } else {
9442 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009443 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009444 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009445 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009446
9447 Value *NewTrueOp = OtherAddOp;
9448 Value *NewFalseOp = NegVal;
9449 if (AddOp != TI)
9450 std::swap(NewTrueOp, NewFalseOp);
9451 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009452 SelectInst::Create(CondVal, NewTrueOp,
9453 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009454
9455 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009456 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009457 }
9458 }
9459 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009460
Chris Lattnere576b912004-04-09 23:46:01 +00009461 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009462 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009463 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9464 if (FoldI)
9465 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009466 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009467
9468 if (BinaryOperator::isNot(CondVal)) {
9469 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9470 SI.setOperand(1, FalseVal);
9471 SI.setOperand(2, TrueVal);
9472 return &SI;
9473 }
9474
Chris Lattner3d69f462004-03-12 05:52:32 +00009475 return 0;
9476}
9477
Dan Gohmaneee962e2008-04-10 18:43:06 +00009478/// EnforceKnownAlignment - If the specified pointer points to an object that
9479/// we control, modify the object's alignment to PrefAlign. This isn't
9480/// often possible though. If alignment is important, a more reliable approach
9481/// is to simply align all global variables and allocation instructions to
9482/// their preferred alignment from the beginning.
9483///
9484static unsigned EnforceKnownAlignment(Value *V,
9485 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009486
Dan Gohmaneee962e2008-04-10 18:43:06 +00009487 User *U = dyn_cast<User>(V);
9488 if (!U) return Align;
9489
Dan Gohmanca178902009-07-17 20:47:02 +00009490 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009491 default: break;
9492 case Instruction::BitCast:
9493 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9494 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009495 // If all indexes are zero, it is just the alignment of the base pointer.
9496 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009497 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009498 if (!isa<Constant>(*i) ||
9499 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009500 AllZeroOperands = false;
9501 break;
9502 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009503
9504 if (AllZeroOperands) {
9505 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009506 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009507 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009508 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009509 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009510 }
9511
9512 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9513 // If there is a large requested alignment and we can, bump up the alignment
9514 // of the global.
9515 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009516 if (GV->getAlignment() >= PrefAlign)
9517 Align = GV->getAlignment();
9518 else {
9519 GV->setAlignment(PrefAlign);
9520 Align = PrefAlign;
9521 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009522 }
9523 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9524 // If there is a requested alignment and if this is an alloca, round up. We
9525 // don't do this for malloc, because some systems can't respect the request.
9526 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009527 if (AI->getAlignment() >= PrefAlign)
9528 Align = AI->getAlignment();
9529 else {
9530 AI->setAlignment(PrefAlign);
9531 Align = PrefAlign;
9532 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009533 }
9534 }
9535
9536 return Align;
9537}
9538
9539/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9540/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9541/// and it is more than the alignment of the ultimate object, see if we can
9542/// increase the alignment of the ultimate object, making this check succeed.
9543unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9544 unsigned PrefAlign) {
9545 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9546 sizeof(PrefAlign) * CHAR_BIT;
9547 APInt Mask = APInt::getAllOnesValue(BitWidth);
9548 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9549 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9550 unsigned TrailZ = KnownZero.countTrailingOnes();
9551 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9552
9553 if (PrefAlign > Align)
9554 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9555
9556 // We don't need to make any adjustment.
9557 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009558}
9559
Chris Lattnerf497b022008-01-13 23:50:23 +00009560Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009561 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009562 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009563 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009564 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009565
9566 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009567 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009568 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009569 return MI;
9570 }
9571
9572 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9573 // load/store.
9574 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9575 if (MemOpLength == 0) return 0;
9576
Chris Lattner37ac6082008-01-14 00:28:35 +00009577 // Source and destination pointer types are always "i8*" for intrinsic. See
9578 // if the size is something we can handle with a single primitive load/store.
9579 // A single load+store correctly handles overlapping memory in the memmove
9580 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009581 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009582 if (Size == 0) return MI; // Delete this mem transfer.
9583
9584 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009585 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009586
Chris Lattner37ac6082008-01-14 00:28:35 +00009587 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009588 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009589 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009590
9591 // Memcpy forces the use of i8* for the source and destination. That means
9592 // that if you're using memcpy to move one double around, you'll get a cast
9593 // from double* to i8*. We'd much rather use a double load+store rather than
9594 // an i64 load+store, here because this improves the odds that the source or
9595 // dest address will be promotable. See if we can find a better type than the
9596 // integer datatype.
9597 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9598 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009599 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009600 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9601 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009602 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009603 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9604 if (STy->getNumElements() == 1)
9605 SrcETy = STy->getElementType(0);
9606 else
9607 break;
9608 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9609 if (ATy->getNumElements() == 1)
9610 SrcETy = ATy->getElementType();
9611 else
9612 break;
9613 } else
9614 break;
9615 }
9616
Dan Gohman8f8e2692008-05-23 01:52:21 +00009617 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009618 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009619 }
9620 }
9621
9622
Chris Lattnerf497b022008-01-13 23:50:23 +00009623 // If the memcpy/memmove provides better alignment info than we can
9624 // infer, use it.
9625 SrcAlign = std::max(SrcAlign, CopyAlign);
9626 DstAlign = std::max(DstAlign, CopyAlign);
9627
9628 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9629 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009630 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9631 InsertNewInstBefore(L, *MI);
9632 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9633
9634 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009635 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009636 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009637}
Chris Lattner3d69f462004-03-12 05:52:32 +00009638
Chris Lattner69ea9d22008-04-30 06:39:11 +00009639Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9640 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009641 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009642 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009643 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009644 return MI;
9645 }
9646
9647 // Extract the length and alignment and fill if they are constant.
9648 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9649 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009650 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009651 return 0;
9652 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009653 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009654
9655 // If the length is zero, this is a no-op
9656 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9657
9658 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9659 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009660 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009661
9662 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009663 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009664
9665 // Alignment 0 is identity for alignment 1 for memset, but not store.
9666 if (Alignment == 0) Alignment = 1;
9667
9668 // Extract the fill value and store.
9669 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009670 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009671 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009672
9673 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009674 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009675 return MI;
9676 }
9677
9678 return 0;
9679}
9680
9681
Chris Lattner8b0ea312006-01-13 20:11:04 +00009682/// visitCallInst - CallInst simplification. This mostly only handles folding
9683/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9684/// the heavy lifting.
9685///
Chris Lattner9fe38862003-06-19 17:00:31 +00009686Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009687 // If the caller function is nounwind, mark the call as nounwind, even if the
9688 // callee isn't.
9689 if (CI.getParent()->getParent()->doesNotThrow() &&
9690 !CI.doesNotThrow()) {
9691 CI.setDoesNotThrow();
9692 return &CI;
9693 }
9694
9695
9696
Chris Lattner8b0ea312006-01-13 20:11:04 +00009697 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9698 if (!II) return visitCallSite(&CI);
9699
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009700 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9701 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009702 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009703 bool Changed = false;
9704
9705 // memmove/cpy/set of zero bytes is a noop.
9706 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9707 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9708
Chris Lattner35b9e482004-10-12 04:52:52 +00009709 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009710 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009711 // Replace the instruction with just byte operations. We would
9712 // transform other cases to loads/stores, but we don't know if
9713 // alignment is sufficient.
9714 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009715 }
9716
Chris Lattner35b9e482004-10-12 04:52:52 +00009717 // If we have a memmove and the source operation is a constant global,
9718 // then the source and dest pointers can't alias, so we can change this
9719 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009720 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009721 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9722 if (GVSrc->isConstant()) {
9723 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009724 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9725 const Type *Tys[1];
9726 Tys[0] = CI.getOperand(3)->getType();
9727 CI.setOperand(0,
9728 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009729 Changed = true;
9730 }
Chris Lattnera935db82008-05-28 05:30:41 +00009731
9732 // memmove(x,x,size) -> noop.
9733 if (MMI->getSource() == MMI->getDest())
9734 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009735 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009736
Chris Lattner95a959d2006-03-06 20:18:44 +00009737 // If we can determine a pointer alignment that is bigger than currently
9738 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009739 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009740 if (Instruction *I = SimplifyMemTransfer(MI))
9741 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009742 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9743 if (Instruction *I = SimplifyMemSet(MSI))
9744 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009745 }
9746
Chris Lattner8b0ea312006-01-13 20:11:04 +00009747 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009748 }
9749
9750 switch (II->getIntrinsicID()) {
9751 default: break;
9752 case Intrinsic::bswap:
9753 // bswap(bswap(x)) -> x
9754 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9755 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9756 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9757 break;
9758 case Intrinsic::ppc_altivec_lvx:
9759 case Intrinsic::ppc_altivec_lvxl:
9760 case Intrinsic::x86_sse_loadu_ps:
9761 case Intrinsic::x86_sse2_loadu_pd:
9762 case Intrinsic::x86_sse2_loadu_dq:
9763 // Turn PPC lvx -> load if the pointer is known aligned.
9764 // Turn X86 loadups -> load if the pointer is known aligned.
9765 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9766 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009767 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009768 CI);
9769 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009770 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009771 break;
9772 case Intrinsic::ppc_altivec_stvx:
9773 case Intrinsic::ppc_altivec_stvxl:
9774 // Turn stvx -> store if the pointer is known aligned.
9775 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9776 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009777 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009778 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9779 return new StoreInst(II->getOperand(1), Ptr);
9780 }
9781 break;
9782 case Intrinsic::x86_sse_storeu_ps:
9783 case Intrinsic::x86_sse2_storeu_pd:
9784 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009785 // Turn X86 storeu -> store if the pointer is known aligned.
9786 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9787 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009788 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009789 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9790 return new StoreInst(II->getOperand(2), Ptr);
9791 }
9792 break;
9793
9794 case Intrinsic::x86_sse_cvttss2si: {
9795 // These intrinsics only demands the 0th element of its input vector. If
9796 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009797 unsigned VWidth =
9798 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9799 APInt DemandedElts(VWidth, 1);
9800 APInt UndefElts(VWidth, 0);
9801 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009802 UndefElts)) {
9803 II->setOperand(1, V);
9804 return II;
9805 }
9806 break;
9807 }
9808
9809 case Intrinsic::ppc_altivec_vperm:
9810 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9811 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9812 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009813
Chris Lattner0521e3c2008-06-18 04:33:20 +00009814 // Check that all of the elements are integer constants or undefs.
9815 bool AllEltsOk = true;
9816 for (unsigned i = 0; i != 16; ++i) {
9817 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9818 !isa<UndefValue>(Mask->getOperand(i))) {
9819 AllEltsOk = false;
9820 break;
9821 }
9822 }
9823
9824 if (AllEltsOk) {
9825 // Cast the input vectors to byte vectors.
9826 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9827 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009828 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009829
Chris Lattner0521e3c2008-06-18 04:33:20 +00009830 // Only extract each element once.
9831 Value *ExtractedElts[32];
9832 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9833
Chris Lattnere2ed0572006-04-06 19:19:17 +00009834 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009835 if (isa<UndefValue>(Mask->getOperand(i)))
9836 continue;
9837 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9838 Idx &= 31; // Match the hardware behavior.
9839
9840 if (ExtractedElts[Idx] == 0) {
9841 Instruction *Elt =
Eric Christophera3500da2009-07-25 02:28:41 +00009842 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
Owen Anderson1d0be152009-08-13 21:58:54 +00009843 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009844 InsertNewInstBefore(Elt, CI);
9845 ExtractedElts[Idx] = Elt;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009846 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009847
Chris Lattner0521e3c2008-06-18 04:33:20 +00009848 // Insert this value into the result vector.
9849 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
Owen Anderson1d0be152009-08-13 21:58:54 +00009850 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
Owen Anderson9adc0ab2009-07-14 23:09:55 +00009851 "tmp");
Chris Lattner0521e3c2008-06-18 04:33:20 +00009852 InsertNewInstBefore(cast<Instruction>(Result), CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00009853 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009854 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009855 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009856 }
9857 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009858
Chris Lattner0521e3c2008-06-18 04:33:20 +00009859 case Intrinsic::stackrestore: {
9860 // If the save is right next to the restore, remove the restore. This can
9861 // happen when variable allocas are DCE'd.
9862 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9863 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9864 BasicBlock::iterator BI = SS;
9865 if (&*++BI == II)
9866 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009867 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009868 }
9869
9870 // Scan down this block to see if there is another stack restore in the
9871 // same block without an intervening call/alloca.
9872 BasicBlock::iterator BI = II;
9873 TerminatorInst *TI = II->getParent()->getTerminator();
9874 bool CannotRemove = false;
9875 for (++BI; &*BI != TI; ++BI) {
9876 if (isa<AllocaInst>(BI)) {
9877 CannotRemove = true;
9878 break;
9879 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009880 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9881 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9882 // If there is a stackrestore below this one, remove this one.
9883 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9884 return EraseInstFromFunction(CI);
9885 // Otherwise, ignore the intrinsic.
9886 } else {
9887 // If we found a non-intrinsic call, we can't remove the stack
9888 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009889 CannotRemove = true;
9890 break;
9891 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009892 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009893 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009894
9895 // If the stack restore is in a return/unwind block and if there are no
9896 // allocas or calls between the restore and the return, nuke the restore.
9897 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9898 return EraseInstFromFunction(CI);
9899 break;
9900 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009901 }
9902
Chris Lattner8b0ea312006-01-13 20:11:04 +00009903 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009904}
9905
9906// InvokeInst simplification
9907//
9908Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009909 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009910}
9911
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009912/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9913/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009914static bool isSafeToEliminateVarargsCast(const CallSite CS,
9915 const CastInst * const CI,
9916 const TargetData * const TD,
9917 const int ix) {
9918 if (!CI->isLosslessCast())
9919 return false;
9920
9921 // The size of ByVal arguments is derived from the type, so we
9922 // can't change to a type with a different size. If the size were
9923 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009924 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009925 return true;
9926
9927 const Type* SrcTy =
9928 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9929 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9930 if (!SrcTy->isSized() || !DstTy->isSized())
9931 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009932 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009933 return false;
9934 return true;
9935}
9936
Chris Lattnera44d8a22003-10-07 22:32:43 +00009937// visitCallSite - Improvements for call and invoke instructions.
9938//
9939Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009940 bool Changed = false;
9941
9942 // If the callee is a constexpr cast of a function, attempt to move the cast
9943 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009944 if (transformConstExprCastCall(CS)) return 0;
9945
Chris Lattner6c266db2003-10-07 22:54:13 +00009946 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009947
Chris Lattner08b22ec2005-05-13 07:09:09 +00009948 if (Function *CalleeF = dyn_cast<Function>(Callee))
9949 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9950 Instruction *OldCall = CS.getInstruction();
9951 // If the call and callee calling conventions don't match, this call must
9952 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009953 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009954 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009955 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009956 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009957 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009958 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9959 return EraseInstFromFunction(*OldCall);
9960 return 0;
9961 }
9962
Chris Lattner17be6352004-10-18 02:59:09 +00009963 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9964 // This instruction is not reachable, just remove it. We insert a store to
9965 // undef so that we know that this code is not reachable, despite the fact
9966 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009967 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009968 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009969 CS.getInstruction());
9970
9971 if (!CS.getInstruction()->use_empty())
9972 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009973 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009974
9975 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9976 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009977 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009978 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009979 }
Chris Lattner17be6352004-10-18 02:59:09 +00009980 return EraseInstFromFunction(*CS.getInstruction());
9981 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009982
Duncan Sandscdb6d922007-09-17 10:26:40 +00009983 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9984 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9985 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9986 return transformCallThroughTrampoline(CS);
9987
Chris Lattner6c266db2003-10-07 22:54:13 +00009988 const PointerType *PTy = cast<PointerType>(Callee->getType());
9989 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9990 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009991 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009992 // See if we can optimize any arguments passed through the varargs area of
9993 // the call.
9994 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009995 E = CS.arg_end(); I != E; ++I, ++ix) {
9996 CastInst *CI = dyn_cast<CastInst>(*I);
9997 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9998 *I = CI->getOperand(0);
9999 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010000 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010001 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010002 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010003
Duncan Sandsf0c33542007-12-19 21:13:37 +000010004 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010005 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010006 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010007 Changed = true;
10008 }
10009
Chris Lattner6c266db2003-10-07 22:54:13 +000010010 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010011}
10012
Chris Lattner9fe38862003-06-19 17:00:31 +000010013// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10014// attempt to move the cast to the arguments of the call/invoke.
10015//
10016bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10017 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10018 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010019 if (CE->getOpcode() != Instruction::BitCast ||
10020 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010021 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010022 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010023 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010024 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010025
10026 // Okay, this is a cast from a function to a different type. Unless doing so
10027 // would cause a type conversion of one of our arguments, change this call to
10028 // be a direct call with arguments casted to the appropriate types.
10029 //
10030 const FunctionType *FT = Callee->getFunctionType();
10031 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010032 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010033
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010034 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010035 return false; // TODO: Handle multiple return values.
10036
Chris Lattnerf78616b2004-01-14 06:06:08 +000010037 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010038 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010039 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010040 // Conversion is ok if changing from one pointer type to another or from
10041 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010042 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010043 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010044 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010045 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010046 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010047
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010048 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010049 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010050 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010051 return false; // Cannot transform this return value.
10052
Chris Lattner58d74912008-03-12 17:45:29 +000010053 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010054 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010055 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010056 return false; // Attribute not compatible with transformed value.
10057 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010058
Chris Lattnerf78616b2004-01-14 06:06:08 +000010059 // If the callsite is an invoke instruction, and the return value is used by
10060 // a PHI node in a successor, we cannot change the return type of the call
10061 // because there is no place to put the cast instruction (without breaking
10062 // the critical edge). Bail out in this case.
10063 if (!Caller->use_empty())
10064 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10065 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10066 UI != E; ++UI)
10067 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10068 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010069 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010070 return false;
10071 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010072
10073 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10074 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010075
Chris Lattner9fe38862003-06-19 17:00:31 +000010076 CallSite::arg_iterator AI = CS.arg_begin();
10077 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10078 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010079 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010080
10081 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010082 return false; // Cannot transform this parameter value.
10083
Devang Patel19c87462008-09-26 22:53:05 +000010084 if (CallerPAL.getParamAttributes(i + 1)
10085 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010086 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010087
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010088 // Converting from one pointer type to another or between a pointer and an
10089 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010090 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010091 (TD && ((isa<PointerType>(ParamTy) ||
10092 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10093 (isa<PointerType>(ActTy) ||
10094 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010095 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010096 }
10097
10098 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010099 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010100 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010101
Chris Lattner58d74912008-03-12 17:45:29 +000010102 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10103 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010104 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010105 // won't be dropping them. Check that these extra arguments have attributes
10106 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010107 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10108 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010109 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010110 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010111 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010112 return false;
10113 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010114
Chris Lattner9fe38862003-06-19 17:00:31 +000010115 // Okay, we decided that this is a safe thing to do: go ahead and start
10116 // inserting cast instructions as necessary...
10117 std::vector<Value*> Args;
10118 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010119 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010120 attrVec.reserve(NumCommonArgs);
10121
10122 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010123 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010124
10125 // If the return value is not being used, the type may not be compatible
10126 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010127 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010128
10129 // Add the new return attributes.
10130 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010131 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010132
10133 AI = CS.arg_begin();
10134 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10135 const Type *ParamTy = FT->getParamType(i);
10136 if ((*AI)->getType() == ParamTy) {
10137 Args.push_back(*AI);
10138 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010139 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010140 false, ParamTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010141 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +000010142 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010144
10145 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010146 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010147 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010148 }
10149
10150 // If the function takes more arguments than the call was taking, add them
10151 // now...
10152 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010153 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010154
10155 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010156 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010157 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010158 errs() << "WARNING: While resolving call to function '"
10159 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010160 } else {
10161 // Add all of the arguments in their promoted form to the arg list...
10162 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10163 const Type *PTy = getPromotedType((*AI)->getType());
10164 if (PTy != (*AI)->getType()) {
10165 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +000010166 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10167 PTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010168 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +000010169 InsertNewInstBefore(Cast, *Caller);
10170 Args.push_back(Cast);
10171 } else {
10172 Args.push_back(*AI);
10173 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010174
Duncan Sandse1e520f2008-01-13 08:02:44 +000010175 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010176 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010177 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010178 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010179 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010180 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010181
Devang Patel19c87462008-09-26 22:53:05 +000010182 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10183 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10184
Owen Anderson1d0be152009-08-13 21:58:54 +000010185 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010186 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010187
Eric Christophera66297a2009-07-25 02:45:27 +000010188 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10189 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010190
Chris Lattner9fe38862003-06-19 17:00:31 +000010191 Instruction *NC;
10192 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010193 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010194 Args.begin(), Args.end(),
10195 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010196 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010197 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010198 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010199 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10200 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010201 CallInst *CI = cast<CallInst>(Caller);
10202 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010203 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010204 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010205 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010206 }
10207
Chris Lattner6934a042007-02-11 01:23:03 +000010208 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010209 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010210 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010211 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010212 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010213 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010214 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010215
10216 // If this is an invoke instruction, we should insert it after the first
10217 // non-phi, instruction in the normal successor block.
10218 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010219 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010220 InsertNewInstBefore(NC, *I);
10221 } else {
10222 // Otherwise, it's a call, just insert cast right after the call instr
10223 InsertNewInstBefore(NC, *Caller);
10224 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010225 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010226 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010227 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010228 }
10229 }
10230
Owen Anderson1d0be152009-08-13 21:58:54 +000010231 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010232 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010233 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010234 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010235 return true;
10236}
10237
Duncan Sandscdb6d922007-09-17 10:26:40 +000010238// transformCallThroughTrampoline - Turn a call to a function created by the
10239// init_trampoline intrinsic into a direct call to the underlying function.
10240//
10241Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10242 Value *Callee = CS.getCalledValue();
10243 const PointerType *PTy = cast<PointerType>(Callee->getType());
10244 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010245 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010246
10247 // If the call already has the 'nest' attribute somewhere then give up -
10248 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010249 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010250 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010251
10252 IntrinsicInst *Tramp =
10253 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10254
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010255 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010256 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10257 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10258
Devang Patel05988662008-09-25 21:00:45 +000010259 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010260 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010261 unsigned NestIdx = 1;
10262 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010263 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010264
10265 // Look for a parameter marked with the 'nest' attribute.
10266 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10267 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010268 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010269 // Record the parameter type and any other attributes.
10270 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010271 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010272 break;
10273 }
10274
10275 if (NestTy) {
10276 Instruction *Caller = CS.getInstruction();
10277 std::vector<Value*> NewArgs;
10278 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10279
Devang Patel05988662008-09-25 21:00:45 +000010280 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010281 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010282
Duncan Sandscdb6d922007-09-17 10:26:40 +000010283 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010284 // mean appending it. Likewise for attributes.
10285
Devang Patel19c87462008-09-26 22:53:05 +000010286 // Add any result attributes.
10287 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010288 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010289
Duncan Sandscdb6d922007-09-17 10:26:40 +000010290 {
10291 unsigned Idx = 1;
10292 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10293 do {
10294 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010295 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010296 Value *NestVal = Tramp->getOperand(3);
10297 if (NestVal->getType() != NestTy)
10298 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10299 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010300 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010301 }
10302
10303 if (I == E)
10304 break;
10305
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010306 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010307 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010308 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010309 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010310 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010311
10312 ++Idx, ++I;
10313 } while (1);
10314 }
10315
Devang Patel19c87462008-09-26 22:53:05 +000010316 // Add any function attributes.
10317 if (Attributes Attr = Attrs.getFnAttributes())
10318 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10319
Duncan Sandscdb6d922007-09-17 10:26:40 +000010320 // The trampoline may have been bitcast to a bogus type (FTy).
10321 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010322 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323
Duncan Sandscdb6d922007-09-17 10:26:40 +000010324 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010325 NewTypes.reserve(FTy->getNumParams()+1);
10326
Duncan Sandscdb6d922007-09-17 10:26:40 +000010327 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010328 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010329 {
10330 unsigned Idx = 1;
10331 FunctionType::param_iterator I = FTy->param_begin(),
10332 E = FTy->param_end();
10333
10334 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010335 if (Idx == NestIdx)
10336 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010337 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010338
10339 if (I == E)
10340 break;
10341
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010342 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010343 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010344
10345 ++Idx, ++I;
10346 } while (1);
10347 }
10348
10349 // Replace the trampoline call with a direct call. Let the generic
10350 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010351 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010352 FTy->isVarArg());
10353 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010354 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010355 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010356 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010357 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10358 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010359
10360 Instruction *NewCaller;
10361 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010362 NewCaller = InvokeInst::Create(NewCallee,
10363 II->getNormalDest(), II->getUnwindDest(),
10364 NewArgs.begin(), NewArgs.end(),
10365 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010366 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010367 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010368 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010369 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10370 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010371 if (cast<CallInst>(Caller)->isTailCall())
10372 cast<CallInst>(NewCaller)->setTailCall();
10373 cast<CallInst>(NewCaller)->
10374 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010375 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010376 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010377 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010378 Caller->replaceAllUsesWith(NewCaller);
10379 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010380 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010381 return 0;
10382 }
10383 }
10384
10385 // Replace the trampoline call with a direct call. Since there is no 'nest'
10386 // parameter, there is no need to adjust the argument list. Let the generic
10387 // code sort out any function type mismatches.
10388 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010389 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010390 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010391 CS.setCalledFunction(NewCallee);
10392 return CS.getInstruction();
10393}
10394
Chris Lattner7da52b22006-11-01 04:51:18 +000010395/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10396/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10397/// and a single binop.
10398Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10399 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010400 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010401 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010402 Value *LHSVal = FirstInst->getOperand(0);
10403 Value *RHSVal = FirstInst->getOperand(1);
10404
10405 const Type *LHSType = LHSVal->getType();
10406 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010407
10408 // Scan to see if all operands are the same opcode, all have one use, and all
10409 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010410 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010411 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010412 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010413 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010414 // types or GEP's with different index types.
10415 I->getOperand(0)->getType() != LHSType ||
10416 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010417 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010418
10419 // If they are CmpInst instructions, check their predicates
10420 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10421 if (cast<CmpInst>(I)->getPredicate() !=
10422 cast<CmpInst>(FirstInst)->getPredicate())
10423 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010424
10425 // Keep track of which operand needs a phi node.
10426 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10427 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010428 }
10429
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;
Chris Lattner05f18922008-12-01 02:34:36 +000010483
10484 // Scan to see if all operands are the same opcode, all have one use, and all
10485 // kill their operands (i.e. the operands have one use).
10486 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10487 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10488 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10489 GEP->getNumOperands() != FirstInst->getNumOperands())
10490 return 0;
10491
Chris Lattner36d3e322009-02-21 00:46:50 +000010492 // Keep track of whether or not all GEPs are of alloca pointers.
10493 if (AllBasePointersAreAllocas &&
10494 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10495 !GEP->hasAllConstantIndices()))
10496 AllBasePointersAreAllocas = false;
10497
Chris Lattner05f18922008-12-01 02:34:36 +000010498 // Compare the operand lists.
10499 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10500 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10501 continue;
10502
10503 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10504 // if one of the PHIs has a constant for the index. The index may be
10505 // substantially cheaper to compute for the constants, so making it a
10506 // variable index could pessimize the path. This also handles the case
10507 // for struct indices, which must always be constant.
10508 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10509 isa<ConstantInt>(GEP->getOperand(op)))
10510 return 0;
10511
10512 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10513 return 0;
10514 FixedOperands[op] = 0; // Needs a PHI.
10515 }
10516 }
10517
Chris Lattner36d3e322009-02-21 00:46:50 +000010518 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010519 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010520 // offset calculation, but all the predecessors will have to materialize the
10521 // stack address into a register anyway. We'd actually rather *clone* the
10522 // load up into the predecessors so that we have a load of a gep of an alloca,
10523 // which can usually all be folded into the load.
10524 if (AllBasePointersAreAllocas)
10525 return 0;
10526
Chris Lattner05f18922008-12-01 02:34:36 +000010527 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10528 // that is variable.
10529 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10530
10531 bool HasAnyPHIs = false;
10532 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10533 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10534 Value *FirstOp = FirstInst->getOperand(i);
10535 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10536 FirstOp->getName()+".pn");
10537 InsertNewInstBefore(NewPN, PN);
10538
10539 NewPN->reserveOperandSpace(e);
10540 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10541 OperandPhis[i] = NewPN;
10542 FixedOperands[i] = NewPN;
10543 HasAnyPHIs = true;
10544 }
10545
10546
10547 // Add all operands to the new PHIs.
10548 if (HasAnyPHIs) {
10549 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10550 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10551 BasicBlock *InBB = PN.getIncomingBlock(i);
10552
10553 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10554 if (PHINode *OpPhi = OperandPhis[op])
10555 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10556 }
10557 }
10558
10559 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010560 GetElementPtrInst *GEP =
10561 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10562 FixedOperands.end());
10563 if (cast<GEPOperator>(FirstInst)->isInBounds())
10564 cast<GEPOperator>(GEP)->setIsInBounds(true);
10565 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010566}
10567
10568
Chris Lattner21550882009-02-23 05:56:17 +000010569/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10570/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010571/// obvious the value of the load is not changed from the point of the load to
10572/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010573///
10574/// Finally, it is safe, but not profitable, to sink a load targetting a
10575/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10576/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010577static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010578 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10579
10580 for (++BBI; BBI != E; ++BBI)
10581 if (BBI->mayWriteToMemory())
10582 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010583
10584 // Check for non-address taken alloca. If not address-taken already, it isn't
10585 // profitable to do this xform.
10586 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10587 bool isAddressTaken = false;
10588 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10589 UI != E; ++UI) {
10590 if (isa<LoadInst>(UI)) continue;
10591 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10592 // If storing TO the alloca, then the address isn't taken.
10593 if (SI->getOperand(1) == AI) continue;
10594 }
10595 isAddressTaken = true;
10596 break;
10597 }
10598
Chris Lattner36d3e322009-02-21 00:46:50 +000010599 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010600 return false;
10601 }
10602
Chris Lattner36d3e322009-02-21 00:46:50 +000010603 // If this load is a load from a GEP with a constant offset from an alloca,
10604 // then we don't want to sink it. In its present form, it will be
10605 // load [constant stack offset]. Sinking it will cause us to have to
10606 // materialize the stack addresses in each predecessor in a register only to
10607 // do a shared load from register in the successor.
10608 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10609 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10610 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10611 return false;
10612
Chris Lattner76c73142006-11-01 07:13:54 +000010613 return true;
10614}
10615
Chris Lattner9fe38862003-06-19 17:00:31 +000010616
Chris Lattnerbac32862004-11-14 19:13:23 +000010617// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10618// operator and they all are only used by the PHI, PHI together their
10619// inputs, and do the operation once, to the result of the PHI.
10620Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10621 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10622
10623 // Scan the instruction, looking for input operations that can be folded away.
10624 // If all input operands to the phi are the same instruction (e.g. a cast from
10625 // the same type or "+42") we can pull the operation through the PHI, reducing
10626 // code size and simplifying code.
10627 Constant *ConstantOp = 0;
10628 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010629 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010630 if (isa<CastInst>(FirstInst)) {
10631 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010632 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010633 // Can fold binop, compare or shift here if the RHS is a constant,
10634 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010635 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010636 if (ConstantOp == 0)
10637 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010638 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10639 isVolatile = LI->isVolatile();
10640 // We can't sink the load if the loaded value could be modified between the
10641 // load and the PHI.
10642 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010643 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010644 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010645
10646 // If the PHI is of volatile loads and the load block has multiple
10647 // successors, sinking it would remove a load of the volatile value from
10648 // the path through the other successor.
10649 if (isVolatile &&
10650 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10651 return 0;
10652
Chris Lattner9c080502006-11-01 07:43:41 +000010653 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010654 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010655 } else {
10656 return 0; // Cannot fold this operation.
10657 }
10658
10659 // Check to see if all arguments are the same operation.
10660 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10661 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10662 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010663 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010664 return 0;
10665 if (CastSrcTy) {
10666 if (I->getOperand(0)->getType() != CastSrcTy)
10667 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010668 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010669 // We can't sink the load if the loaded value could be modified between
10670 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010671 if (LI->isVolatile() != isVolatile ||
10672 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010673 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010674 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010675
Chris Lattner71042962008-07-08 17:18:32 +000010676 // If the PHI is of volatile loads and the load block has multiple
10677 // successors, sinking it would remove a load of the volatile value from
10678 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010679 if (isVolatile &&
10680 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10681 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010682
Chris Lattnerbac32862004-11-14 19:13:23 +000010683 } else if (I->getOperand(1) != ConstantOp) {
10684 return 0;
10685 }
10686 }
10687
10688 // Okay, they are all the same operation. Create a new PHI node of the
10689 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010690 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10691 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010692 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010693
10694 Value *InVal = FirstInst->getOperand(0);
10695 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010696
10697 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010698 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10699 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10700 if (NewInVal != InVal)
10701 InVal = 0;
10702 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10703 }
10704
10705 Value *PhiVal;
10706 if (InVal) {
10707 // The new PHI unions all of the same values together. This is really
10708 // common, so we handle it intelligently here for compile-time speed.
10709 PhiVal = InVal;
10710 delete NewPN;
10711 } else {
10712 InsertNewInstBefore(NewPN, PN);
10713 PhiVal = NewPN;
10714 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010715
Chris Lattnerbac32862004-11-14 19:13:23 +000010716 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010717 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010718 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010719 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010720 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010721 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010722 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010723 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010724 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10725
10726 // If this was a volatile load that we are merging, make sure to loop through
10727 // and mark all the input loads as non-volatile. If we don't do this, we will
10728 // insert a new volatile load and the old ones will not be deletable.
10729 if (isVolatile)
10730 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10731 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10732
10733 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010734}
Chris Lattnera1be5662002-05-02 17:06:02 +000010735
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010736/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10737/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010738static bool DeadPHICycle(PHINode *PN,
10739 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010740 if (PN->use_empty()) return true;
10741 if (!PN->hasOneUse()) return false;
10742
10743 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010744 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010745 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010746
10747 // Don't scan crazily complex things.
10748 if (PotentiallyDeadPHIs.size() == 16)
10749 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010750
10751 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10752 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010753
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010754 return false;
10755}
10756
Chris Lattnercf5008a2007-11-06 21:52:06 +000010757/// PHIsEqualValue - Return true if this phi node is always equal to
10758/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10759/// z = some value; x = phi (y, z); y = phi (x, z)
10760static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10761 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10762 // See if we already saw this PHI node.
10763 if (!ValueEqualPHIs.insert(PN))
10764 return true;
10765
10766 // Don't scan crazily complex things.
10767 if (ValueEqualPHIs.size() == 16)
10768 return false;
10769
10770 // Scan the operands to see if they are either phi nodes or are equal to
10771 // the value.
10772 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10773 Value *Op = PN->getIncomingValue(i);
10774 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10775 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10776 return false;
10777 } else if (Op != NonPhiInVal)
10778 return false;
10779 }
10780
10781 return true;
10782}
10783
10784
Chris Lattner473945d2002-05-06 18:06:38 +000010785// PHINode simplification
10786//
Chris Lattner7e708292002-06-25 16:13:24 +000010787Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010788 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010789 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010790
Owen Anderson7e057142006-07-10 22:03:18 +000010791 if (Value *V = PN.hasConstantValue())
10792 return ReplaceInstUsesWith(PN, V);
10793
Owen Anderson7e057142006-07-10 22:03:18 +000010794 // If all PHI operands are the same operation, pull them through the PHI,
10795 // reducing code size.
10796 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010797 isa<Instruction>(PN.getIncomingValue(1)) &&
10798 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10799 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10800 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10801 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010802 PN.getIncomingValue(0)->hasOneUse())
10803 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10804 return Result;
10805
10806 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10807 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10808 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010809 if (PN.hasOneUse()) {
10810 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10811 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010812 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010813 PotentiallyDeadPHIs.insert(&PN);
10814 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010815 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010816 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010817
10818 // If this phi has a single use, and if that use just computes a value for
10819 // the next iteration of a loop, delete the phi. This occurs with unused
10820 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10821 // common case here is good because the only other things that catch this
10822 // are induction variable analysis (sometimes) and ADCE, which is only run
10823 // late.
10824 if (PHIUser->hasOneUse() &&
10825 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10826 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010827 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010828 }
10829 }
Owen Anderson7e057142006-07-10 22:03:18 +000010830
Chris Lattnercf5008a2007-11-06 21:52:06 +000010831 // We sometimes end up with phi cycles that non-obviously end up being the
10832 // same value, for example:
10833 // z = some value; x = phi (y, z); y = phi (x, z)
10834 // where the phi nodes don't necessarily need to be in the same block. Do a
10835 // quick check to see if the PHI node only contains a single non-phi value, if
10836 // so, scan to see if the phi cycle is actually equal to that value.
10837 {
10838 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10839 // Scan for the first non-phi operand.
10840 while (InValNo != NumOperandVals &&
10841 isa<PHINode>(PN.getIncomingValue(InValNo)))
10842 ++InValNo;
10843
10844 if (InValNo != NumOperandVals) {
10845 Value *NonPhiInVal = PN.getOperand(InValNo);
10846
10847 // Scan the rest of the operands to see if there are any conflicts, if so
10848 // there is no need to recursively scan other phis.
10849 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10850 Value *OpVal = PN.getIncomingValue(InValNo);
10851 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10852 break;
10853 }
10854
10855 // If we scanned over all operands, then we have one unique value plus
10856 // phi values. Scan PHI nodes to see if they all merge in each other or
10857 // the value.
10858 if (InValNo == NumOperandVals) {
10859 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10860 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10861 return ReplaceInstUsesWith(PN, NonPhiInVal);
10862 }
10863 }
10864 }
Chris Lattner60921c92003-12-19 05:58:40 +000010865 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010866}
10867
Chris Lattner7e708292002-06-25 16:13:24 +000010868Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010869 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010870 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010871 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010872 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010873 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010874
Chris Lattnere87597f2004-10-16 18:11:37 +000010875 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010876 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010877
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010878 bool HasZeroPointerIndex = false;
10879 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10880 HasZeroPointerIndex = C->isNullValue();
10881
10882 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010883 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010884
Chris Lattner28977af2004-04-05 01:30:19 +000010885 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010886 if (TD) {
10887 bool MadeChange = false;
10888 unsigned PtrSize = TD->getPointerSizeInBits();
10889
10890 gep_type_iterator GTI = gep_type_begin(GEP);
10891 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10892 I != E; ++I, ++GTI) {
10893 if (!isa<SequentialType>(*GTI)) continue;
10894
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010895 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010896 // to what we need. If narrower, sign-extend it to what we need. This
10897 // explicit cast can make subsequent optimizations more obvious.
10898 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10899
10900 if (OpBits == PtrSize)
10901 continue;
10902
10903 Instruction::CastOps Opc =
10904 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
10905 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
10906 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010907 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010908 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010909 }
Chris Lattner28977af2004-04-05 01:30:19 +000010910
Chris Lattner90ac28c2002-08-02 19:29:35 +000010911 // Combine Indices - If the source pointer to this getelementptr instruction
10912 // is a getelementptr instruction, combine the indices of the two
10913 // getelementptr instructions into a single instruction.
10914 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010915 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010916 // Note that if our source is a gep chain itself that we wait for that
10917 // chain to be resolved before we perform this transformation. This
10918 // avoids us creating a TON of code in some cases.
10919 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010920 if (GetElementPtrInst *SrcGEP =
10921 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10922 if (SrcGEP->getNumOperands() == 2)
10923 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010924
Chris Lattner72588fc2007-02-15 22:48:32 +000010925 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010926
10927 // Find out whether the last index in the source GEP is a sequential idx.
10928 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010929 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10930 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010931 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010932
Chris Lattner90ac28c2002-08-02 19:29:35 +000010933 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010934 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010935 // Replace: gep (gep %P, long B), long A, ...
10936 // With: T = long A+B; gep %P, T, ...
10937 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010938 Value *Sum;
10939 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10940 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010941 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010942 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010943 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010944 Sum = SO1;
10945 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010946 // If they aren't the same type, then the input hasn't been processed
10947 // by the loop above yet (which canonicalizes sequential index types to
10948 // intptr_t). Just avoid transforming this until the input has been
10949 // normalized.
10950 if (SO1->getType() != GO1->getType())
10951 return 0;
Chris Lattner620ce142004-05-07 22:09:22 +000010952 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Chris Lattnerccf4b342009-08-30 04:49:01 +000010953 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
Chris Lattner620ce142004-05-07 22:09:22 +000010954 else {
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010955 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner48595f12004-06-10 02:07:29 +000010956 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +000010957 }
Chris Lattner28977af2004-04-05 01:30:19 +000010958 }
Chris Lattner620ce142004-05-07 22:09:22 +000010959
Chris Lattnerab984842009-08-30 05:30:55 +000010960 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010961 if (Src->getNumOperands() == 2) {
10962 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010963 GEP.setOperand(1, Sum);
10964 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010965 }
Chris Lattnerab984842009-08-30 05:30:55 +000010966 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010967 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010968 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010969 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010970 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010971 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010972 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010973 Indices.append(Src->op_begin()+1, Src->op_end());
10974 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010975 }
10976
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010977 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000010978 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010979 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010980 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010981 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010982 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10983 return NewGEP;
10984 }
Chris Lattner6e24d832009-08-30 05:00:50 +000010985 }
10986
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010987 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10988 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010989 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10990
10991 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010992 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10993 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010994 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010995 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10996 // into : GEP i8* X, ...
10997 //
Chris Lattnereed48272005-09-13 00:40:14 +000010998 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010999 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11000 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011001 if (const ArrayType *CATy =
11002 dyn_cast<ArrayType>(CPTy->getElementType())) {
11003 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11004 if (CATy->getElementType() == XTy->getElementType()) {
11005 // -> GEP i8* X, ...
11006 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011007 GetElementPtrInst *NewGEP =
11008 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11009 GEP.getName());
11010 if (cast<GEPOperator>(&GEP)->isInBounds())
11011 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11012 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011013 } else if (const ArrayType *XATy =
11014 dyn_cast<ArrayType>(XTy->getElementType())) {
11015 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000011016 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011017 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000011018 // At this point, we know that the cast source type is a pointer
11019 // to an array of the same type as the destination pointer
11020 // array. Because the array type is never stepped over (there
11021 // is a leading zero) we can fold the cast into this GEP.
11022 GEP.setOperand(0, X);
11023 return &GEP;
11024 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000011025 }
11026 }
Chris Lattnereed48272005-09-13 00:40:14 +000011027 } else if (GEP.getNumOperands() == 2) {
11028 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011029 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11030 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000011031 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11032 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011033 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000011034 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11035 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000011036 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011037 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011038 Idx[1] = GEP.getOperand(1);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011039 GetElementPtrInst *NewGEP =
11040 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11041 if (cast<GEPOperator>(&GEP)->isInBounds())
11042 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11043 Value *V = InsertNewInstBefore(NewGEP, GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +000011044 // V and GEP are both pointer types --> BitCast
11045 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011046 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000011047
11048 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011049 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000011050 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011051 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000011052
Owen Anderson1d0be152009-08-13 21:58:54 +000011053 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011054 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011055 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011056
11057 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11058 // allow either a mul, shift, or constant here.
11059 Value *NewIdx = 0;
11060 ConstantInt *Scale = 0;
11061 if (ArrayEltSize == 1) {
11062 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011063 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011064 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011065 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011066 Scale = CI;
11067 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11068 if (Inst->getOpcode() == Instruction::Shl &&
11069 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011070 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11071 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011072 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011073 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011074 NewIdx = Inst->getOperand(0);
11075 } else if (Inst->getOpcode() == Instruction::Mul &&
11076 isa<ConstantInt>(Inst->getOperand(1))) {
11077 Scale = cast<ConstantInt>(Inst->getOperand(1));
11078 NewIdx = Inst->getOperand(0);
11079 }
11080 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011081
Chris Lattner7835cdd2005-09-13 18:36:04 +000011082 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011083 // out, perform the transformation. Note, we don't know whether Scale is
11084 // signed or not. We'll use unsigned version of division/modulo
11085 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011086 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011087 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011088 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011089 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011090 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011091 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11092 false /*ZExt*/);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011093 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011094 NewIdx = InsertNewInstBefore(Sc, GEP);
11095 }
11096
11097 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011098 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011099 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011100 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +000011101 Instruction *NewGEP =
Gabor Greif051a9502008-04-06 20:25:17 +000011102 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011103 if (cast<GEPOperator>(&GEP)->isInBounds())
11104 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011105 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11106 // The NewGEP must be pointer typed, so must the old one -> BitCast
11107 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011108 }
11109 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011110 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011111 }
Chris Lattner58407792009-01-09 04:53:57 +000011112
Chris Lattner46cd5a12009-01-09 05:44:56 +000011113 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011114 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011115 /// Y = gep X, <...constant indices...>
11116 /// into a gep of the original struct. This is important for SROA and alias
11117 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011118 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011119 if (TD &&
11120 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011121 // Determine how much the GEP moves the pointer. We are guaranteed to get
11122 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011123 ConstantInt *OffsetV =
11124 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011125 int64_t Offset = OffsetV->getSExtValue();
11126
11127 // If this GEP instruction doesn't move the pointer, just replace the GEP
11128 // with a bitcast of the real input to the dest type.
11129 if (Offset == 0) {
11130 // If the bitcast is of an allocation, and the allocation will be
11131 // converted to match the type of the cast, don't touch this.
11132 if (isa<AllocationInst>(BCI->getOperand(0))) {
11133 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11134 if (Instruction *I = visitBitCast(*BCI)) {
11135 if (I != BCI) {
11136 I->takeName(BCI);
11137 BCI->getParent()->getInstList().insert(BCI, I);
11138 ReplaceInstUsesWith(*BCI, I);
11139 }
11140 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011141 }
Chris Lattner58407792009-01-09 04:53:57 +000011142 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011143 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011144 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011145
11146 // Otherwise, if the offset is non-zero, we need to find out if there is a
11147 // field at Offset in 'A's type. If so, we can pull the cast through the
11148 // GEP.
11149 SmallVector<Value*, 8> NewIndices;
11150 const Type *InTy =
11151 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011152 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011153 Instruction *NGEP =
11154 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11155 NewIndices.end());
11156 if (NGEP->getType() == GEP.getType()) return NGEP;
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011157 if (cast<GEPOperator>(&GEP)->isInBounds())
11158 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011159 InsertNewInstBefore(NGEP, GEP);
11160 NGEP->takeName(&GEP);
11161 return new BitCastInst(NGEP, GEP.getType());
11162 }
Chris Lattner58407792009-01-09 04:53:57 +000011163 }
11164 }
11165
Chris Lattner8a2a3112001-12-14 16:52:21 +000011166 return 0;
11167}
11168
Chris Lattner0864acf2002-11-04 16:18:53 +000011169Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11170 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011171 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011172 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11173 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011174 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011175 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011176
11177 // Create and insert the replacement instruction...
11178 if (isa<MallocInst>(AI))
Owen Anderson50dead02009-07-15 23:53:25 +000011179 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011180 else {
11181 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Owen Anderson50dead02009-07-15 23:53:25 +000011182 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011183 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011184
11185 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +000011186
Chris Lattner0864acf2002-11-04 16:18:53 +000011187 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011188 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011189 //
11190 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011191 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011192
11193 // Now that I is pointing to the first non-allocation-inst in the block,
11194 // insert our getelementptr instruction...
11195 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011196 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011197 Value *Idx[2];
11198 Idx[0] = NullIdx;
11199 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011200 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11201 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011202 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011203
11204 // Now make everything use the getelementptr instead of the original
11205 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011206 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011207 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011208 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011209 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011210 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011211
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011212 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011213 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011214 // Note that we only do this for alloca's, because malloc should allocate
11215 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011216 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011217 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011218
11219 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11220 if (AI.getAlignment() == 0)
11221 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11222 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011223
Chris Lattner0864acf2002-11-04 16:18:53 +000011224 return 0;
11225}
11226
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011227Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11228 Value *Op = FI.getOperand(0);
11229
Chris Lattner17be6352004-10-18 02:59:09 +000011230 // free undef -> unreachable.
11231 if (isa<UndefValue>(Op)) {
11232 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011233 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011234 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011235 return EraseInstFromFunction(FI);
11236 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011237
Chris Lattner6160e852004-02-28 04:57:37 +000011238 // If we have 'free null' delete the instruction. This can happen in stl code
11239 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011240 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011241 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011242
11243 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11244 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11245 FI.setOperand(0, CI->getOperand(0));
11246 return &FI;
11247 }
11248
11249 // Change free (gep X, 0,0,0,0) into free(X)
11250 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11251 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011252 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011253 FI.setOperand(0, GEPI->getOperand(0));
11254 return &FI;
11255 }
11256 }
11257
11258 // Change free(malloc) into nothing, if the malloc has a single use.
11259 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11260 if (MI->hasOneUse()) {
11261 EraseInstFromFunction(FI);
11262 return EraseInstFromFunction(*MI);
11263 }
Chris Lattner6160e852004-02-28 04:57:37 +000011264
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011265 return 0;
11266}
11267
11268
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011269/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011270static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011271 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011272 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011273 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011274 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011275
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011276 if (TD) {
11277 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11278 // Instead of loading constant c string, use corresponding integer value
11279 // directly if string length is small enough.
11280 std::string Str;
11281 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11282 unsigned len = Str.length();
11283 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11284 unsigned numBits = Ty->getPrimitiveSizeInBits();
11285 // Replace LI with immediate integer store.
11286 if ((numBits >> 3) == len + 1) {
11287 APInt StrVal(numBits, 0);
11288 APInt SingleChar(numBits, 0);
11289 if (TD->isLittleEndian()) {
11290 for (signed i = len-1; i >= 0; i--) {
11291 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11292 StrVal = (StrVal << 8) | SingleChar;
11293 }
11294 } else {
11295 for (unsigned i = 0; i < len; i++) {
11296 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11297 StrVal = (StrVal << 8) | SingleChar;
11298 }
11299 // Append NULL at the end.
11300 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011301 StrVal = (StrVal << 8) | SingleChar;
11302 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011303 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011304 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011305 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011306 }
11307 }
11308 }
11309
Mon P Wang6753f952009-02-07 22:19:29 +000011310 const PointerType *DestTy = cast<PointerType>(CI->getType());
11311 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011312 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011313
11314 // If the address spaces don't match, don't eliminate the cast.
11315 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11316 return 0;
11317
Chris Lattnerb89e0712004-07-13 01:49:43 +000011318 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011319
Reid Spencer42230162007-01-22 05:51:25 +000011320 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011321 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011322 // If the source is an array, the code below will not succeed. Check to
11323 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11324 // constants.
11325 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11326 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11327 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011328 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011329 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011330 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011331 SrcTy = cast<PointerType>(CastOp->getType());
11332 SrcPTy = SrcTy->getElementType();
11333 }
11334
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011335 if (IC.getTargetData() &&
11336 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011337 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011338 // Do not allow turning this into a load of an integer, which is then
11339 // casted to a pointer, this pessimizes pointer analysis a lot.
11340 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011341 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11342 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011343
Chris Lattnerf9527852005-01-31 04:50:46 +000011344 // Okay, we are casting from one integer or pointer type to another of
11345 // the same size. Instead of casting the pointer before the load, cast
11346 // the result of the loaded value.
11347 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11348 CI->getName(),
11349 LI.isVolatile()),LI);
11350 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011351 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011352 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011353 }
11354 }
11355 return 0;
11356}
11357
Chris Lattner833b8a42003-06-26 05:06:25 +000011358Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11359 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011360
Dan Gohman9941f742007-07-20 16:34:21 +000011361 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011362 if (TD) {
11363 unsigned KnownAlign =
11364 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11365 if (KnownAlign >
11366 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11367 LI.getAlignment()))
11368 LI.setAlignment(KnownAlign);
11369 }
Dan Gohman9941f742007-07-20 16:34:21 +000011370
Chris Lattner37366c12005-05-01 04:24:53 +000011371 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011372 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011373 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011374 return Res;
11375
11376 // None of the following transforms are legal for volatile loads.
11377 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011378
Dan Gohman2276a7b2008-10-15 23:19:35 +000011379 // Do really simple store-to-load forwarding and load CSE, to catch cases
11380 // where there are several consequtive memory accesses to the same location,
11381 // separated by a few arithmetic operations.
11382 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011383 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11384 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011385
Christopher Lambb15147e2007-12-29 07:56:53 +000011386 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11387 const Value *GEPI0 = GEPI->getOperand(0);
11388 // TODO: Consider a target hook for valid address spaces for this xform.
11389 if (isa<ConstantPointerNull>(GEPI0) &&
11390 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011391 // Insert a new store to null instruction before the load to indicate
11392 // that this code is not reachable. We do this instead of inserting
11393 // an unreachable instruction directly because we cannot modify the
11394 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011395 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011396 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011397 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011398 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011399 }
Chris Lattner37366c12005-05-01 04:24:53 +000011400
Chris Lattnere87597f2004-10-16 18:11:37 +000011401 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011402 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011403 // TODO: Consider a target hook for valid address spaces for this xform.
11404 if (isa<UndefValue>(C) || (C->isNullValue() &&
11405 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011406 // Insert a new store to null instruction before the load to indicate that
11407 // this code is not reachable. We do this instead of inserting an
11408 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011409 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011410 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011411 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011412 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011413
Chris Lattnere87597f2004-10-16 18:11:37 +000011414 // Instcombine load (constant global) into the value loaded.
11415 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011416 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011417 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011418
Chris Lattnere87597f2004-10-16 18:11:37 +000011419 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011420 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011421 if (CE->getOpcode() == Instruction::GetElementPtr) {
11422 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011423 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011424 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011425 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011426 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011427 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011428 if (CE->getOperand(0)->isNullValue()) {
11429 // Insert a new store to null instruction before the load to indicate
11430 // that this code is not reachable. We do this instead of inserting
11431 // an unreachable instruction directly because we cannot modify the
11432 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011433 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011434 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011435 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011436 }
11437
Reid Spencer3da59db2006-11-27 01:05:10 +000011438 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011439 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011440 return Res;
11441 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011442 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011443 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011444
11445 // If this load comes from anywhere in a constant global, and if the global
11446 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011447 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011448 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011449 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011450 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011451 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011452 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011453 }
11454 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011455
Chris Lattner37366c12005-05-01 04:24:53 +000011456 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011457 // Change select and PHI nodes to select values instead of addresses: this
11458 // helps alias analysis out a lot, allows many others simplifications, and
11459 // exposes redundancy in the code.
11460 //
11461 // Note that we cannot do the transformation unless we know that the
11462 // introduced loads cannot trap! Something like this is valid as long as
11463 // the condition is always false: load (select bool %C, int* null, int* %G),
11464 // but it would not be valid if we transformed it to load from null
11465 // unconditionally.
11466 //
11467 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11468 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011469 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11470 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011471 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011472 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011473 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +000011474 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greif051a9502008-04-06 20:25:17 +000011475 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011476 }
11477
Chris Lattner684fe212004-09-23 15:46:00 +000011478 // load (select (cond, null, P)) -> load P
11479 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11480 if (C->isNullValue()) {
11481 LI.setOperand(0, SI->getOperand(2));
11482 return &LI;
11483 }
11484
11485 // load (select (cond, P, null)) -> load P
11486 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11487 if (C->isNullValue()) {
11488 LI.setOperand(0, SI->getOperand(1));
11489 return &LI;
11490 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011491 }
11492 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011493 return 0;
11494}
11495
Reid Spencer55af2b52007-01-19 21:20:31 +000011496/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011497/// when possible. This makes it generally easy to do alias analysis and/or
11498/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011499static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11500 User *CI = cast<User>(SI.getOperand(1));
11501 Value *CastOp = CI->getOperand(0);
11502
11503 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011504 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11505 if (SrcTy == 0) return 0;
11506
11507 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011508
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011509 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11510 return 0;
11511
Chris Lattner3914f722009-01-24 01:00:13 +000011512 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11513 /// to its first element. This allows us to handle things like:
11514 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11515 /// on 32-bit hosts.
11516 SmallVector<Value*, 4> NewGEPIndices;
11517
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011518 // If the source is an array, the code below will not succeed. Check to
11519 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11520 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011521 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11522 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011523 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011524 NewGEPIndices.push_back(Zero);
11525
11526 while (1) {
11527 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011528 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011529 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011530 NewGEPIndices.push_back(Zero);
11531 SrcPTy = STy->getElementType(0);
11532 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11533 NewGEPIndices.push_back(Zero);
11534 SrcPTy = ATy->getElementType();
11535 } else {
11536 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011537 }
Chris Lattner3914f722009-01-24 01:00:13 +000011538 }
11539
Owen Andersondebcb012009-07-29 22:17:13 +000011540 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011541 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011542
11543 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11544 return 0;
11545
Chris Lattner71759c42009-01-16 20:12:52 +000011546 // If the pointers point into different address spaces or if they point to
11547 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011548 if (!IC.getTargetData() ||
11549 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011550 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011551 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11552 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011553 return 0;
11554
11555 // Okay, we are casting from one integer or pointer type to another of
11556 // the same size. Instead of casting the pointer before
11557 // the store, cast the value to be stored.
11558 Value *NewCast;
11559 Value *SIOp0 = SI.getOperand(0);
11560 Instruction::CastOps opcode = Instruction::BitCast;
11561 const Type* CastSrcTy = SIOp0->getType();
11562 const Type* CastDstTy = SrcPTy;
11563 if (isa<PointerType>(CastDstTy)) {
11564 if (CastSrcTy->isInteger())
11565 opcode = Instruction::IntToPtr;
11566 } else if (isa<IntegerType>(CastDstTy)) {
11567 if (isa<PointerType>(SIOp0->getType()))
11568 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011569 }
Chris Lattner3914f722009-01-24 01:00:13 +000011570
11571 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11572 // emit a GEP to index into its first field.
11573 if (!NewGEPIndices.empty()) {
11574 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011575 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner3914f722009-01-24 01:00:13 +000011576 NewGEPIndices.size());
11577 else
11578 CastOp = IC.InsertNewInstBefore(
11579 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11580 NewGEPIndices.end()), SI);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011581 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011582 }
11583
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011584 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Andersonbaf3c402009-07-29 18:55:55 +000011585 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011586 else
11587 NewCast = IC.InsertNewInstBefore(
11588 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11589 SI);
11590 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011591}
11592
Chris Lattner4aebaee2008-11-27 08:56:30 +000011593/// equivalentAddressValues - Test if A and B will obviously have the same
11594/// value. This includes recognizing that %t0 and %t1 will have the same
11595/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011596/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011597/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011598/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011599/// %t2 = load i32* %t1
11600///
11601static bool equivalentAddressValues(Value *A, Value *B) {
11602 // Test if the values are trivially equivalent.
11603 if (A == B) return true;
11604
11605 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011606 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11607 // its only used to compare two uses within the same basic block, which
11608 // means that they'll always either have the same value or one of them
11609 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011610 if (isa<BinaryOperator>(A) ||
11611 isa<CastInst>(A) ||
11612 isa<PHINode>(A) ||
11613 isa<GetElementPtrInst>(A))
11614 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011615 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011616 return true;
11617
11618 // Otherwise they may not be equivalent.
11619 return false;
11620}
11621
Dale Johannesen4945c652009-03-03 21:26:39 +000011622// If this instruction has two uses, one of which is a llvm.dbg.declare,
11623// return the llvm.dbg.declare.
11624DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11625 if (!V->hasNUses(2))
11626 return 0;
11627 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11628 UI != E; ++UI) {
11629 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11630 return DI;
11631 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11632 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11633 return DI;
11634 }
11635 }
11636 return 0;
11637}
11638
Chris Lattner2f503e62005-01-31 05:36:43 +000011639Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11640 Value *Val = SI.getOperand(0);
11641 Value *Ptr = SI.getOperand(1);
11642
11643 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011644 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011645 ++NumCombined;
11646 return 0;
11647 }
Chris Lattner836692d2007-01-15 06:51:56 +000011648
11649 // If the RHS is an alloca with a single use, zapify the store, making the
11650 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011651 // If the RHS is an alloca with a two uses, the other one being a
11652 // llvm.dbg.declare, zapify the store and the declare, making the
11653 // alloca dead. We must do this to prevent declare's from affecting
11654 // codegen.
11655 if (!SI.isVolatile()) {
11656 if (Ptr->hasOneUse()) {
11657 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011658 EraseInstFromFunction(SI);
11659 ++NumCombined;
11660 return 0;
11661 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011662 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11663 if (isa<AllocaInst>(GEP->getOperand(0))) {
11664 if (GEP->getOperand(0)->hasOneUse()) {
11665 EraseInstFromFunction(SI);
11666 ++NumCombined;
11667 return 0;
11668 }
11669 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11670 EraseInstFromFunction(*DI);
11671 EraseInstFromFunction(SI);
11672 ++NumCombined;
11673 return 0;
11674 }
11675 }
11676 }
11677 }
11678 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11679 EraseInstFromFunction(*DI);
11680 EraseInstFromFunction(SI);
11681 ++NumCombined;
11682 return 0;
11683 }
Chris Lattner836692d2007-01-15 06:51:56 +000011684 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011685
Dan Gohman9941f742007-07-20 16:34:21 +000011686 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011687 if (TD) {
11688 unsigned KnownAlign =
11689 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11690 if (KnownAlign >
11691 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11692 SI.getAlignment()))
11693 SI.setAlignment(KnownAlign);
11694 }
Dan Gohman9941f742007-07-20 16:34:21 +000011695
Dale Johannesenacb51a32009-03-03 01:43:03 +000011696 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011697 // stores to the same location, separated by a few arithmetic operations. This
11698 // situation often occurs with bitfield accesses.
11699 BasicBlock::iterator BBI = &SI;
11700 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11701 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011702 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011703 // Don't count debug info directives, lest they affect codegen,
11704 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11705 // It is necessary for correctness to skip those that feed into a
11706 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011707 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011708 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011709 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011710 continue;
11711 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011712
11713 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11714 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011715 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11716 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011717 ++NumDeadStore;
11718 ++BBI;
11719 EraseInstFromFunction(*PrevSI);
11720 continue;
11721 }
11722 break;
11723 }
11724
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011725 // If this is a load, we have to stop. However, if the loaded value is from
11726 // the pointer we're loading and is producing the pointer we're storing,
11727 // then *this* store is dead (X = load P; store X -> P).
11728 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011729 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11730 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011731 EraseInstFromFunction(SI);
11732 ++NumCombined;
11733 return 0;
11734 }
11735 // Otherwise, this is a load from some other location. Stores before it
11736 // may not be dead.
11737 break;
11738 }
11739
Chris Lattner9ca96412006-02-08 03:25:32 +000011740 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011741 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011742 break;
11743 }
11744
11745
11746 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011747
11748 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011749 if (isa<ConstantPointerNull>(Ptr) &&
11750 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011751 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011752 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011753 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011754 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011755 ++NumCombined;
11756 }
11757 return 0; // Do not modify these!
11758 }
11759
11760 // store undef, Ptr -> noop
11761 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011762 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011763 ++NumCombined;
11764 return 0;
11765 }
11766
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011767 // If the pointer destination is a cast, see if we can fold the cast into the
11768 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011769 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011770 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11771 return Res;
11772 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011773 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011774 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11775 return Res;
11776
Chris Lattner408902b2005-09-12 23:23:25 +000011777
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011778 // If this store is the last instruction in the basic block (possibly
11779 // excepting debug info instructions and the pointer bitcasts that feed
11780 // into them), and if the block ends with an unconditional branch, try
11781 // to move it to the successor block.
11782 BBI = &SI;
11783 do {
11784 ++BBI;
11785 } while (isa<DbgInfoIntrinsic>(BBI) ||
11786 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011787 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011788 if (BI->isUnconditional())
11789 if (SimplifyStoreAtEndOfBlock(SI))
11790 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011791
Chris Lattner2f503e62005-01-31 05:36:43 +000011792 return 0;
11793}
11794
Chris Lattner3284d1f2007-04-15 00:07:55 +000011795/// SimplifyStoreAtEndOfBlock - Turn things like:
11796/// if () { *P = v1; } else { *P = v2 }
11797/// into a phi node with a store in the successor.
11798///
Chris Lattner31755a02007-04-15 01:02:18 +000011799/// Simplify things like:
11800/// *P = v1; if () { *P = v2; }
11801/// into a phi node with a store in the successor.
11802///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011803bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11804 BasicBlock *StoreBB = SI.getParent();
11805
11806 // Check to see if the successor block has exactly two incoming edges. If
11807 // so, see if the other predecessor contains a store to the same location.
11808 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011809 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011810
11811 // Determine whether Dest has exactly two predecessors and, if so, compute
11812 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011813 pred_iterator PI = pred_begin(DestBB);
11814 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011815 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011816 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011817 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011818 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011819 return false;
11820
11821 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011822 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011823 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011824 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011825 }
Chris Lattner31755a02007-04-15 01:02:18 +000011826 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011827 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011828
11829 // Bail out if all the relevant blocks aren't distinct (this can happen,
11830 // for example, if SI is in an infinite loop)
11831 if (StoreBB == DestBB || OtherBB == DestBB)
11832 return false;
11833
Chris Lattner31755a02007-04-15 01:02:18 +000011834 // Verify that the other block ends in a branch and is not otherwise empty.
11835 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011836 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011837 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011838 return false;
11839
Chris Lattner31755a02007-04-15 01:02:18 +000011840 // If the other block ends in an unconditional branch, check for the 'if then
11841 // else' case. there is an instruction before the branch.
11842 StoreInst *OtherStore = 0;
11843 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011844 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011845 // Skip over debugging info.
11846 while (isa<DbgInfoIntrinsic>(BBI) ||
11847 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11848 if (BBI==OtherBB->begin())
11849 return false;
11850 --BBI;
11851 }
11852 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011853 OtherStore = dyn_cast<StoreInst>(BBI);
11854 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11855 return false;
11856 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011857 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011858 // destinations is StoreBB, then we have the if/then case.
11859 if (OtherBr->getSuccessor(0) != StoreBB &&
11860 OtherBr->getSuccessor(1) != StoreBB)
11861 return false;
11862
11863 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011864 // if/then triangle. See if there is a store to the same ptr as SI that
11865 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011866 for (;; --BBI) {
11867 // Check to see if we find the matching store.
11868 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11869 if (OtherStore->getOperand(1) != SI.getOperand(1))
11870 return false;
11871 break;
11872 }
Eli Friedman6903a242008-06-13 22:02:12 +000011873 // If we find something that may be using or overwriting the stored
11874 // value, or if we run out of instructions, we can't do the xform.
11875 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011876 BBI == OtherBB->begin())
11877 return false;
11878 }
11879
11880 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011881 // make sure nothing reads or overwrites the stored value in
11882 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011883 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11884 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011885 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011886 return false;
11887 }
11888 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011889
Chris Lattner31755a02007-04-15 01:02:18 +000011890 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011891 Value *MergedVal = OtherStore->getOperand(0);
11892 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011893 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011894 PN->reserveOperandSpace(2);
11895 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011896 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11897 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011898 }
11899
11900 // Advance to a place where it is safe to insert the new store and
11901 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011902 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011903 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11904 OtherStore->isVolatile()), *BBI);
11905
11906 // Nuke the old stores.
11907 EraseInstFromFunction(SI);
11908 EraseInstFromFunction(*OtherStore);
11909 ++NumCombined;
11910 return true;
11911}
11912
Chris Lattner2f503e62005-01-31 05:36:43 +000011913
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011914Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11915 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011916 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011917 BasicBlock *TrueDest;
11918 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011919 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011920 !isa<Constant>(X)) {
11921 // Swap Destinations and condition...
11922 BI.setCondition(X);
11923 BI.setSuccessor(0, FalseDest);
11924 BI.setSuccessor(1, TrueDest);
11925 return &BI;
11926 }
11927
Reid Spencere4d87aa2006-12-23 06:05:41 +000011928 // Cannonicalize fcmp_one -> fcmp_oeq
11929 FCmpInst::Predicate FPred; Value *Y;
11930 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011931 TrueDest, FalseDest)) &&
11932 BI.getCondition()->hasOneUse())
11933 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11934 FPred == FCmpInst::FCMP_OGE) {
11935 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11936 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11937
11938 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011939 BI.setSuccessor(0, FalseDest);
11940 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011941 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011942 return &BI;
11943 }
11944
11945 // Cannonicalize icmp_ne -> icmp_eq
11946 ICmpInst::Predicate IPred;
11947 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011948 TrueDest, FalseDest)) &&
11949 BI.getCondition()->hasOneUse())
11950 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11951 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11952 IPred == ICmpInst::ICMP_SGE) {
11953 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11954 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11955 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011956 BI.setSuccessor(0, FalseDest);
11957 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011958 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011959 return &BI;
11960 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011961
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011962 return 0;
11963}
Chris Lattner0864acf2002-11-04 16:18:53 +000011964
Chris Lattner46238a62004-07-03 00:26:11 +000011965Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11966 Value *Cond = SI.getCondition();
11967 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11968 if (I->getOpcode() == Instruction::Add)
11969 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11970 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11971 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011972 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011973 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011974 AddRHS));
11975 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011976 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011977 return &SI;
11978 }
11979 }
11980 return 0;
11981}
11982
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011983Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011984 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011985
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011986 if (!EV.hasIndices())
11987 return ReplaceInstUsesWith(EV, Agg);
11988
11989 if (Constant *C = dyn_cast<Constant>(Agg)) {
11990 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011991 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011992
11993 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011994 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011995
11996 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11997 // Extract the element indexed by the first index out of the constant
11998 Value *V = C->getOperand(*EV.idx_begin());
11999 if (EV.getNumIndices() > 1)
12000 // Extract the remaining indices out of the constant indexed by the
12001 // first index
12002 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12003 else
12004 return ReplaceInstUsesWith(EV, V);
12005 }
12006 return 0; // Can't handle other constants
12007 }
12008 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12009 // We're extracting from an insertvalue instruction, compare the indices
12010 const unsigned *exti, *exte, *insi, *inse;
12011 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12012 exte = EV.idx_end(), inse = IV->idx_end();
12013 exti != exte && insi != inse;
12014 ++exti, ++insi) {
12015 if (*insi != *exti)
12016 // The insert and extract both reference distinctly different elements.
12017 // This means the extract is not influenced by the insert, and we can
12018 // replace the aggregate operand of the extract with the aggregate
12019 // operand of the insert. i.e., replace
12020 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12021 // %E = extractvalue { i32, { i32 } } %I, 0
12022 // with
12023 // %E = extractvalue { i32, { i32 } } %A, 0
12024 return ExtractValueInst::Create(IV->getAggregateOperand(),
12025 EV.idx_begin(), EV.idx_end());
12026 }
12027 if (exti == exte && insi == inse)
12028 // Both iterators are at the end: Index lists are identical. Replace
12029 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12030 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12031 // with "i32 42"
12032 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12033 if (exti == exte) {
12034 // The extract list is a prefix of the insert list. i.e. replace
12035 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12036 // %E = extractvalue { i32, { i32 } } %I, 1
12037 // with
12038 // %X = extractvalue { i32, { i32 } } %A, 1
12039 // %E = insertvalue { i32 } %X, i32 42, 0
12040 // by switching the order of the insert and extract (though the
12041 // insertvalue should be left in, since it may have other uses).
12042 Value *NewEV = InsertNewInstBefore(
12043 ExtractValueInst::Create(IV->getAggregateOperand(),
12044 EV.idx_begin(), EV.idx_end()),
12045 EV);
12046 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12047 insi, inse);
12048 }
12049 if (insi == inse)
12050 // The insert list is a prefix of the extract list
12051 // We can simply remove the common indices from the extract and make it
12052 // operate on the inserted value instead of the insertvalue result.
12053 // i.e., replace
12054 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12055 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12056 // with
12057 // %E extractvalue { i32 } { i32 42 }, 0
12058 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12059 exti, exte);
12060 }
12061 // Can't simplify extracts from other values. Note that nested extracts are
12062 // already simplified implicitely by the above (extract ( extract (insert) )
12063 // will be translated into extract ( insert ( extract ) ) first and then just
12064 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000012065 return 0;
12066}
12067
Chris Lattner220b0cf2006-03-05 00:22:33 +000012068/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12069/// is to leave as a vector operation.
12070static bool CheapToScalarize(Value *V, bool isConstant) {
12071 if (isa<ConstantAggregateZero>(V))
12072 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012073 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012074 if (isConstant) return true;
12075 // If all elts are the same, we can extract.
12076 Constant *Op0 = C->getOperand(0);
12077 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12078 if (C->getOperand(i) != Op0)
12079 return false;
12080 return true;
12081 }
12082 Instruction *I = dyn_cast<Instruction>(V);
12083 if (!I) return false;
12084
12085 // Insert element gets simplified to the inserted element or is deleted if
12086 // this is constant idx extract element and its a constant idx insertelt.
12087 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12088 isa<ConstantInt>(I->getOperand(2)))
12089 return true;
12090 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12091 return true;
12092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12093 if (BO->hasOneUse() &&
12094 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12095 CheapToScalarize(BO->getOperand(1), isConstant)))
12096 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012097 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12098 if (CI->hasOneUse() &&
12099 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12100 CheapToScalarize(CI->getOperand(1), isConstant)))
12101 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012102
12103 return false;
12104}
12105
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012106/// Read and decode a shufflevector mask.
12107///
12108/// It turns undef elements into values that are larger than the number of
12109/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012110static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12111 unsigned NElts = SVI->getType()->getNumElements();
12112 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12113 return std::vector<unsigned>(NElts, 0);
12114 if (isa<UndefValue>(SVI->getOperand(2)))
12115 return std::vector<unsigned>(NElts, 2*NElts);
12116
12117 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012118 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012119 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12120 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012121 Result.push_back(NElts*2); // undef -> 8
12122 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012123 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012124 return Result;
12125}
12126
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012127/// FindScalarElement - Given a vector and an element number, see if the scalar
12128/// value is already around as a register, for example if it were inserted then
12129/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012130static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012131 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012132 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12133 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012134 unsigned Width = PTy->getNumElements();
12135 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012136 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012137
12138 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012139 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012140 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012141 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012142 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012143 return CP->getOperand(EltNo);
12144 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12145 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012146 if (!isa<ConstantInt>(III->getOperand(2)))
12147 return 0;
12148 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012149
12150 // If this is an insert to the element we are looking for, return the
12151 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012152 if (EltNo == IIElt)
12153 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012154
12155 // Otherwise, the insertelement doesn't modify the value, recurse on its
12156 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012157 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012158 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012159 unsigned LHSWidth =
12160 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012161 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012162 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012163 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012164 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012165 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012166 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012167 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012168 }
12169
12170 // Otherwise, we don't know.
12171 return 0;
12172}
12173
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012174Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012175 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012176 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012177 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012178
Dan Gohman07a96762007-07-16 14:29:03 +000012179 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012180 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012181 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012182
Reid Spencer9d6565a2007-02-15 02:26:10 +000012183 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012184 // If vector val is constant with all elements the same, replace EI with
12185 // that element. When the elements are not identical, we cannot replace yet
12186 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012187 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012188 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012189 if (C->getOperand(i) != op0) {
12190 op0 = 0;
12191 break;
12192 }
12193 if (op0)
12194 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012195 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012196
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012197 // If extracting a specified index from the vector, see if we can recursively
12198 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012199 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012200 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012201 unsigned VectorWidth =
12202 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012203
12204 // If this is extracting an invalid index, turn this into undef, to avoid
12205 // crashing the code below.
12206 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012207 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012208
Chris Lattner867b99f2006-10-05 06:55:50 +000012209 // This instruction only demands the single element from the input vector.
12210 // If the input vector has a single use, simplify it based on this use
12211 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012212 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012213 APInt UndefElts(VectorWidth, 0);
12214 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012215 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012216 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012217 EI.setOperand(0, V);
12218 return &EI;
12219 }
12220 }
12221
Owen Andersond672ecb2009-07-03 00:17:18 +000012222 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012223 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012224
12225 // If the this extractelement is directly using a bitcast from a vector of
12226 // the same number of elements, see if we can find the source element from
12227 // it. In this case, we will end up needing to bitcast the scalars.
12228 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12229 if (const VectorType *VT =
12230 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12231 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012232 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12233 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012234 return new BitCastInst(Elt, EI.getType());
12235 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012236 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012237
Chris Lattner73fa49d2006-05-25 22:53:38 +000012238 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012239 if (I->hasOneUse()) {
12240 // Push extractelement into predecessor operation if legal and
12241 // profitable to do so
12242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012243 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12244 if (CheapToScalarize(BO, isConstantElt)) {
12245 ExtractElementInst *newEI0 =
Eric Christophera3500da2009-07-25 02:28:41 +000012246 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012247 EI.getName()+".lhs");
12248 ExtractElementInst *newEI1 =
Eric Christophera3500da2009-07-25 02:28:41 +000012249 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
Chris Lattner220b0cf2006-03-05 00:22:33 +000012250 EI.getName()+".rhs");
12251 InsertNewInstBefore(newEI0, EI);
12252 InsertNewInstBefore(newEI1, EI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012253 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012254 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012255 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012256 unsigned AS =
12257 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012258 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wang7c4efa62009-08-13 05:12:13 +000012259 PointerType::get(EI.getType(), AS),*I);
Gabor Greifb1dbcd82008-05-15 10:04:30 +000012260 GetElementPtrInst *GEP =
12261 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012262 cast<GEPOperator>(GEP)->setIsInBounds(true);
Mon P Wang7c4efa62009-08-13 05:12:13 +000012263 InsertNewInstBefore(GEP, *I);
12264 LoadInst* Load = new LoadInst(GEP, "tmp");
12265 InsertNewInstBefore(Load, *I);
12266 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012267 }
12268 }
12269 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12270 // Extracting the inserted element?
12271 if (IE->getOperand(2) == EI.getOperand(1))
12272 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12273 // If the inserted and extracted elements are constants, they must not
12274 // be the same value, extract from the pre-inserted value instead.
12275 if (isa<Constant>(IE->getOperand(2)) &&
12276 isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012277 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012278 EI.setOperand(0, IE->getOperand(0));
12279 return &EI;
12280 }
12281 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12282 // If this is extracting an element from a shufflevector, figure out where
12283 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012284 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12285 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012286 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012287 unsigned LHSWidth =
12288 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12289
12290 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012291 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012292 else if (SrcIdx < LHSWidth*2) {
12293 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012294 Src = SVI->getOperand(1);
12295 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012296 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012297 }
Eric Christophera3500da2009-07-25 02:28:41 +000012298 return ExtractElementInst::Create(Src,
Owen Anderson1d0be152009-08-13 21:58:54 +000012299 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012300 }
12301 }
Eli Friedman2451a642009-07-18 23:06:53 +000012302 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012303 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012304 return 0;
12305}
12306
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012307/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12308/// elements from either LHS or RHS, return the shuffle mask and true.
12309/// Otherwise, return false.
12310static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012311 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012312 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012313 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12314 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012315 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012316
12317 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012318 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012319 return true;
12320 } else if (V == LHS) {
12321 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012322 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012323 return true;
12324 } else if (V == RHS) {
12325 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012326 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012327 return true;
12328 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12329 // If this is an insert of an extract from some other vector, include it.
12330 Value *VecOp = IEI->getOperand(0);
12331 Value *ScalarOp = IEI->getOperand(1);
12332 Value *IdxOp = IEI->getOperand(2);
12333
Chris Lattnerd929f062006-04-27 21:14:21 +000012334 if (!isa<ConstantInt>(IdxOp))
12335 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012336 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012337
12338 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
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 Lattnerd929f062006-04-27 21:14:21 +000012342 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012343 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012344 return true;
12345 }
12346 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12347 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012348 EI->getOperand(0)->getType() == V->getType()) {
12349 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012350 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012351
12352 // This must be extracting from either LHS or RHS.
12353 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12354 // Okay, we can handle this if the vector we are insertinting into is
12355 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012356 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012357 // If so, update the mask to reflect the inserted value.
12358 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012359 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012360 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012361 } else {
12362 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012363 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012364 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012365
12366 }
12367 return true;
12368 }
12369 }
12370 }
12371 }
12372 }
12373 // TODO: Handle shufflevector here!
12374
12375 return false;
12376}
12377
12378/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12379/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12380/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012381static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012382 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012383 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012384 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012385 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012386 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012387
12388 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012389 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012390 return V;
12391 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012392 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012393 return V;
12394 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12395 // If this is an insert of an extract from some other vector, include it.
12396 Value *VecOp = IEI->getOperand(0);
12397 Value *ScalarOp = IEI->getOperand(1);
12398 Value *IdxOp = IEI->getOperand(2);
12399
12400 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12401 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12402 EI->getOperand(0)->getType() == V->getType()) {
12403 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012404 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12405 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012406
12407 // Either the extracted from or inserted into vector must be RHSVec,
12408 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012409 if (EI->getOperand(0) == RHS || RHS == 0) {
12410 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012411 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012412 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012413 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012414 return V;
12415 }
12416
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012417 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012418 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12419 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012420 // Everything but the extracted element is replaced with the RHS.
12421 for (unsigned i = 0; i != NumElts; ++i) {
12422 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012423 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012424 }
12425 return V;
12426 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012427
12428 // If this insertelement is a chain that comes from exactly these two
12429 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012430 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12431 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012432 return EI->getOperand(0);
12433
Chris Lattnerefb47352006-04-15 01:39:45 +000012434 }
12435 }
12436 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012437 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012438
12439 // Otherwise, can't do anything fancy. Return an identity vector.
12440 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012441 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012442 return V;
12443}
12444
12445Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12446 Value *VecOp = IE.getOperand(0);
12447 Value *ScalarOp = IE.getOperand(1);
12448 Value *IdxOp = IE.getOperand(2);
12449
Chris Lattner599ded12007-04-09 01:11:16 +000012450 // Inserting an undef or into an undefined place, remove this.
12451 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12452 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012453
Chris Lattnerefb47352006-04-15 01:39:45 +000012454 // If the inserted element was extracted from some other vector, and if the
12455 // indexes are constant, try to turn this into a shufflevector operation.
12456 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12457 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12458 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012459 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012460 unsigned ExtractedIdx =
12461 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012462 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012463
12464 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12465 return ReplaceInstUsesWith(IE, VecOp);
12466
12467 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012468 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012469
12470 // If we are extracting a value from a vector, then inserting it right
12471 // back into the same place, just use the input vector.
12472 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12473 return ReplaceInstUsesWith(IE, VecOp);
12474
12475 // We could theoretically do this for ANY input. However, doing so could
12476 // turn chains of insertelement instructions into a chain of shufflevector
12477 // instructions, and right now we do not merge shufflevectors. As such,
12478 // only do this in a situation where it is clear that there is benefit.
12479 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12480 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12481 // the values of VecOp, except then one read from EIOp0.
12482 // Build a new shuffle mask.
12483 std::vector<Constant*> Mask;
12484 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012485 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012486 else {
12487 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012488 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012489 NumVectorElts));
12490 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012491 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012492 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012493 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012494 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012495 }
12496
12497 // If this insertelement isn't used by some other insertelement, turn it
12498 // (and any insertelements it points to), into one big shuffle.
12499 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12500 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012501 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012502 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012503 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012504 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012505 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012506 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012507 }
12508 }
12509 }
12510
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012511 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12512 APInt UndefElts(VWidth, 0);
12513 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12514 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12515 return &IE;
12516
Chris Lattnerefb47352006-04-15 01:39:45 +000012517 return 0;
12518}
12519
12520
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012521Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12522 Value *LHS = SVI.getOperand(0);
12523 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012524 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012525
12526 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012527
Chris Lattner867b99f2006-10-05 06:55:50 +000012528 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012529 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012530 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012531
Dan Gohman488fbfc2008-09-09 18:11:14 +000012532 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012533
12534 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12535 return 0;
12536
Evan Cheng388df622009-02-03 10:05:09 +000012537 APInt UndefElts(VWidth, 0);
12538 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12539 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012540 LHS = SVI.getOperand(0);
12541 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012542 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012543 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012544
Chris Lattner863bcff2006-05-25 23:48:38 +000012545 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12546 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12547 if (LHS == RHS || isa<UndefValue>(LHS)) {
12548 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012549 // shuffle(undef,undef,mask) -> undef.
12550 return ReplaceInstUsesWith(SVI, LHS);
12551 }
12552
Chris Lattner863bcff2006-05-25 23:48:38 +000012553 // Remap any references to RHS to use LHS.
12554 std::vector<Constant*> Elts;
12555 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012556 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012557 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012558 else {
12559 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012560 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012561 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012562 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012563 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012564 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012565 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012566 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012567 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012568 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012569 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012570 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012571 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012572 LHS = SVI.getOperand(0);
12573 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012574 MadeChange = true;
12575 }
12576
Chris Lattner7b2e27922006-05-26 00:29:06 +000012577 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012578 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012579
Chris Lattner863bcff2006-05-25 23:48:38 +000012580 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12581 if (Mask[i] >= e*2) continue; // Ignore undef values.
12582 // Is this an identity shuffle of the LHS value?
12583 isLHSID &= (Mask[i] == i);
12584
12585 // Is this an identity shuffle of the RHS value?
12586 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012587 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012588
Chris Lattner863bcff2006-05-25 23:48:38 +000012589 // Eliminate identity shuffles.
12590 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12591 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012592
Chris Lattner7b2e27922006-05-26 00:29:06 +000012593 // If the LHS is a shufflevector itself, see if we can combine it with this
12594 // one without producing an unusual shuffle. Here we are really conservative:
12595 // we are absolutely afraid of producing a shuffle mask not in the input
12596 // program, because the code gen may not be smart enough to turn a merged
12597 // shuffle into two specific shuffles: it may produce worse code. As such,
12598 // we only merge two shuffles if the result is one of the two input shuffle
12599 // masks. In this case, merging the shuffles just removes one instruction,
12600 // which we know is safe. This is good for things like turning:
12601 // (splat(splat)) -> splat.
12602 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12603 if (isa<UndefValue>(RHS)) {
12604 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12605
12606 std::vector<unsigned> NewMask;
12607 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12608 if (Mask[i] >= 2*e)
12609 NewMask.push_back(2*e);
12610 else
12611 NewMask.push_back(LHSMask[Mask[i]]);
12612
12613 // If the result mask is equal to the src shuffle or this shuffle mask, do
12614 // the replacement.
12615 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012616 unsigned LHSInNElts =
12617 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012618 std::vector<Constant*> Elts;
12619 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012620 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012621 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012622 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012623 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012624 }
12625 }
12626 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12627 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012628 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012629 }
12630 }
12631 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012632
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012633 return MadeChange ? &SVI : 0;
12634}
12635
12636
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012637
Chris Lattnerea1c4542004-12-08 23:43:58 +000012638
12639/// TryToSinkInstruction - Try to move the specified instruction from its
12640/// current block into the beginning of DestBlock, which can only happen if it's
12641/// safe to move the instruction past all of the instructions between it and the
12642/// end of its block.
12643static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12644 assert(I->hasOneUse() && "Invariants didn't hold!");
12645
Chris Lattner108e9022005-10-27 17:13:11 +000012646 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012647 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012648 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012649
Chris Lattnerea1c4542004-12-08 23:43:58 +000012650 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012651 if (isa<AllocaInst>(I) && I->getParent() ==
12652 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012653 return false;
12654
Chris Lattner96a52a62004-12-09 07:14:34 +000012655 // We can only sink load instructions if there is nothing between the load and
12656 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012657 if (I->mayReadFromMemory()) {
12658 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012659 Scan != E; ++Scan)
12660 if (Scan->mayWriteToMemory())
12661 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012662 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012663
Dan Gohman02dea8b2008-05-23 21:05:58 +000012664 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012665
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012666 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012667 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012668 ++NumSunkInst;
12669 return true;
12670}
12671
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012672
12673/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12674/// all reachable code to the worklist.
12675///
12676/// This has a couple of tricks to make the code faster and more powerful. In
12677/// particular, we constant fold and DCE instructions as we go, to avoid adding
12678/// them to the worklist (this significantly speeds up instcombine on code where
12679/// many instructions are dead or constant). Additionally, if we find a branch
12680/// whose condition is a known constant, we only visit the reachable successors.
12681///
12682static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012683 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012684 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012685 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012686 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012687 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012688
Chris Lattner2c7718a2007-03-23 19:17:18 +000012689 while (!Worklist.empty()) {
12690 BB = Worklist.back();
12691 Worklist.pop_back();
12692
12693 // We have now visited this block! If we've already been here, ignore it.
12694 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012695
12696 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012697 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12698 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012699
Chris Lattner2c7718a2007-03-23 19:17:18 +000012700 // DCE instruction if trivially dead.
12701 if (isInstructionTriviallyDead(Inst)) {
12702 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012703 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012704 Inst->eraseFromParent();
12705 continue;
12706 }
12707
12708 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012709 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012710 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12711 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012712 Inst->replaceAllUsesWith(C);
12713 ++NumConstProp;
12714 Inst->eraseFromParent();
12715 continue;
12716 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012717
Devang Patel7fe1dec2008-11-19 18:56:50 +000012718 // If there are two consecutive llvm.dbg.stoppoint calls then
12719 // it is likely that the optimizer deleted code in between these
12720 // two intrinsics.
12721 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12722 if (DBI_Next) {
12723 if (DBI_Prev
12724 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12725 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012726 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012727 DBI_Prev->eraseFromParent();
12728 }
12729 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012730 } else {
12731 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012732 }
12733
Chris Lattner7a1e9242009-08-30 06:13:40 +000012734 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012735 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012736
12737 // Recursively visit successors. If this is a branch or switch on a
12738 // constant, only visit the reachable successor.
12739 TerminatorInst *TI = BB->getTerminator();
12740 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12741 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12742 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012743 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012744 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012745 continue;
12746 }
12747 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12748 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12749 // See if this is an explicit destination.
12750 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12751 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012752 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012753 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012754 continue;
12755 }
12756
12757 // Otherwise it is the default destination.
12758 Worklist.push_back(SI->getSuccessor(0));
12759 continue;
12760 }
12761 }
12762
12763 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12764 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012765 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012766}
12767
Chris Lattnerec9c3582007-03-03 02:04:50 +000012768bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012769 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012770 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012771
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012772 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12773 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012774
Chris Lattnerb3d59702005-07-07 20:40:38 +000012775 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012776 // Do a depth-first traversal of the function, populate the worklist with
12777 // the reachable instructions. Ignore blocks that are not reachable. Keep
12778 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012779 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012780 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012781
Chris Lattnerb3d59702005-07-07 20:40:38 +000012782 // Do a quick scan over the function. If we find any blocks that are
12783 // unreachable, remove any instructions inside of them. This prevents
12784 // the instcombine code from having to deal with some bad special cases.
12785 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12786 if (!Visited.count(BB)) {
12787 Instruction *Term = BB->getTerminator();
12788 while (Term != BB->begin()) { // Remove instrs bottom-up
12789 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012790
Chris Lattnerbdff5482009-08-23 04:37:46 +000012791 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012792 // A debug intrinsic shouldn't force another iteration if we weren't
12793 // going to do one without it.
12794 if (!isa<DbgInfoIntrinsic>(I)) {
12795 ++NumDeadInst;
12796 Changed = true;
12797 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012798 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012799 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012800 I->eraseFromParent();
12801 }
12802 }
12803 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012804
Chris Lattner873ff012009-08-30 05:55:36 +000012805 while (!Worklist.isEmpty()) {
12806 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012807 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012808
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012809 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012810 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012811 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012812 EraseInstFromFunction(*I);
12813 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012814 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012815 continue;
12816 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012817
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012818 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012819 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012820 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012821
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012822 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012823 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012824 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012825 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012826 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012827 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012828 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012829
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012830 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012831 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012832 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12833 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012834 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12835 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012836 if (NewC != CE) {
12837 i->set(NewC);
12838 Changed = true;
12839 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012840 }
12841
Chris Lattnerea1c4542004-12-08 23:43:58 +000012842 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012843 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012844 BasicBlock *BB = I->getParent();
12845 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12846 if (UserParent != BB) {
12847 bool UserIsSuccessor = false;
12848 // See if the user is one of our successors.
12849 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12850 if (*SI == UserParent) {
12851 UserIsSuccessor = true;
12852 break;
12853 }
12854
12855 // If the user is one of our immediate successors, and if that successor
12856 // only has us as a predecessors (we'd have to split the critical edge
12857 // otherwise), we can keep going.
12858 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12859 next(pred_begin(UserParent)) == pred_end(UserParent))
12860 // Okay, the CFG is simple enough, try to sink this instruction.
12861 Changed |= TryToSinkInstruction(I, UserParent);
12862 }
12863 }
12864
Chris Lattner74381062009-08-30 07:44:24 +000012865 // Now that we have an instruction, try combining it to simplify it.
12866 Builder->SetInsertPoint(I->getParent(), I);
12867
Reid Spencera9b81012007-03-26 17:44:01 +000012868#ifndef NDEBUG
12869 std::string OrigI;
12870#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012871 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012872
Chris Lattner90ac28c2002-08-02 19:29:35 +000012873 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012874 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012875 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012876 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012877 DEBUG(errs() << "IC: Old = " << *I << '\n'
12878 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012879
Chris Lattnerf523d062004-06-09 05:08:07 +000012880 // Everything uses the new instruction now.
12881 I->replaceAllUsesWith(Result);
12882
12883 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012884 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012885 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012886
Chris Lattner6934a042007-02-11 01:23:03 +000012887 // Move the name to the new instruction first.
12888 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012889
12890 // Insert the new instruction into the basic block...
12891 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012892 BasicBlock::iterator InsertPos = I;
12893
12894 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12895 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12896 ++InsertPos;
12897
12898 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012899
Chris Lattner7a1e9242009-08-30 06:13:40 +000012900 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012901 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012902#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012903 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12904 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012905#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012906
Chris Lattner90ac28c2002-08-02 19:29:35 +000012907 // If the instruction was modified, it's possible that it is now dead.
12908 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012909 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012910 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012911 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012912 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012913 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012914 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012915 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012916 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012917 }
12918 }
12919
Chris Lattner873ff012009-08-30 05:55:36 +000012920 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012921 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012922}
12923
Chris Lattnerec9c3582007-03-03 02:04:50 +000012924
12925bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012926 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012927 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012928
Chris Lattner74381062009-08-30 07:44:24 +000012929
12930 /// Builder - This is an IRBuilder that automatically inserts new
12931 /// instructions into the worklist when they are created.
12932 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12933 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12934 InstCombineIRInserter(Worklist));
12935 Builder = &TheBuilder;
12936
Chris Lattnerec9c3582007-03-03 02:04:50 +000012937 bool EverMadeChange = false;
12938
12939 // Iterate while there is work to do.
12940 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012941 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012942 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012943
12944 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012945 return EverMadeChange;
12946}
12947
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012948FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012949 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012950}