blob: 47e6f4d55821667ca0110f833525c43108aff4bb [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.
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000173 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
174 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000175
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000176 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000177 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000178
Owen Andersone922c022009-07-22 00:24:57 +0000179 LLVMContext *Context;
180 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000181
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000182 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000183 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000184
185 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000186
Chris Lattner97e52e42002-04-28 21:27:06 +0000187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000188 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000189 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000190 }
191
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000192 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000193
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000194 // Visitation implementation - Implement instruction combining for different
195 // instruction types. The semantics are as follows:
196 // Return Value:
197 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000198 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000199 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000200 //
Chris Lattner7e708292002-06-25 16:13:24 +0000201 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000202 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000203 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000204 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000205 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000206 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000207 Instruction *visitURem(BinaryOperator &I);
208 Instruction *visitSRem(BinaryOperator &I);
209 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000210 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000211 Instruction *commonRemTransforms(BinaryOperator &I);
212 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000213 Instruction *commonDivTransforms(BinaryOperator &I);
214 Instruction *commonIDivTransforms(BinaryOperator &I);
215 Instruction *visitUDiv(BinaryOperator &I);
216 Instruction *visitSDiv(BinaryOperator &I);
217 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000218 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000219 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000220 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000221 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000222 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000223 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000224 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000225 Instruction *visitOr (BinaryOperator &I);
226 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000227 Instruction *visitShl(BinaryOperator &I);
228 Instruction *visitAShr(BinaryOperator &I);
229 Instruction *visitLShr(BinaryOperator &I);
230 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000231 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
232 Constant *RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000233 Instruction *visitFCmpInst(FCmpInst &I);
234 Instruction *visitICmpInst(ICmpInst &I);
235 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000236 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
237 Instruction *LHS,
238 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000239 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000241
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000242 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000243 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000244 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000245 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000246 Instruction *commonCastTransforms(CastInst &CI);
247 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000248 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000249 Instruction *visitTrunc(TruncInst &CI);
250 Instruction *visitZExt(ZExtInst &CI);
251 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000252 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000253 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000254 Instruction *visitFPToUI(FPToUIInst &FI);
255 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000256 Instruction *visitUIToFP(CastInst &CI);
257 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000258 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000259 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000260 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000261 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
262 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000263 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000264 Instruction *visitSelectInst(SelectInst &SI);
265 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000266 Instruction *visitCallInst(CallInst &CI);
267 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000268 Instruction *visitPHINode(PHINode &PN);
269 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000270 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000271 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000272 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000273 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000274 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000275 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000276 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000277 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000278 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000279 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000280
281 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000282 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000283
Chris Lattner9fe38862003-06-19 17:00:31 +0000284 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000285 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000286 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000287 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000288 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000290 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000291 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
292
Chris Lattner9fe38862003-06-19 17:00:31 +0000293
Chris Lattner28977af2004-04-05 01:30:19 +0000294 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000295 // InsertNewInstBefore - insert an instruction New before instruction Old
296 // in the program. Add the new instruction to the worklist.
297 //
Chris Lattner955f3312004-09-28 21:48:02 +0000298 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000299 assert(New && New->getParent() == 0 &&
300 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000301 BasicBlock *BB = Old.getParent();
302 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000303 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000304 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000305 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000306
Chris Lattner8b170942002-08-09 23:47:40 +0000307 // ReplaceInstUsesWith - This method is to be used when an instruction is
308 // found to be dead, replacable with another preexisting expression. Here
309 // we add all uses of I to the worklist, replace all uses of I with the new
310 // value, then return I, so that the inst combiner will know that I was
311 // modified.
312 //
313 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000314 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000315
316 // If we are replacing the instruction with itself, this must be in a
317 // segment of unreachable code, so just clobber the instruction.
318 if (&I == V)
319 V = UndefValue::get(I.getType());
320
321 I.replaceAllUsesWith(V);
322 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000323 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000324
325 // EraseInstFromFunction - When dealing with an instruction that has side
326 // effects or produces a void value, we can't rely on DCE to delete the
327 // instruction. Instead, visit methods should return the value returned by
328 // this function.
329 Instruction *EraseInstFromFunction(Instruction &I) {
330 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000331 // Make sure that we reprocess all operands now that we reduced their
332 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000333 if (I.getNumOperands() < 8) {
334 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
335 if (Instruction *Op = dyn_cast<Instruction>(*i))
336 Worklist.Add(Op);
337 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000338 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000339 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000340 return 0; // Don't do anything with FI
341 }
Chris Lattner173234a2008-06-02 01:18:21 +0000342
343 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
344 APInt &KnownOne, unsigned Depth = 0) const {
345 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
346 }
347
348 bool MaskedValueIsZero(Value *V, const APInt &Mask,
349 unsigned Depth = 0) const {
350 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
351 }
352 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
353 return llvm::ComputeNumSignBits(Op, TD, Depth);
354 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000355
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000356 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000357
Reid Spencere4d87aa2006-12-23 06:05:41 +0000358 /// SimplifyCommutative - This performs a few simplifications for
359 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000360 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000361
Reid Spencere4d87aa2006-12-23 06:05:41 +0000362 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
363 /// most-complex to least-complex order.
364 bool SimplifyCompare(CmpInst &I);
365
Chris Lattner886ab6c2009-01-31 08:15:18 +0000366 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
367 /// based on the demanded bits.
368 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
369 APInt& KnownZero, APInt& KnownOne,
370 unsigned Depth);
371 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000372 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000373 unsigned Depth=0);
374
375 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
376 /// SimplifyDemandedBits knows about. See if the instruction has any
377 /// properties that allow us to simplify its operands.
378 bool SimplifyDemandedInstructionBits(Instruction &Inst);
379
Evan Cheng388df622009-02-03 10:05:09 +0000380 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
381 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000382
Chris Lattner4e998b22004-09-29 05:07:12 +0000383 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
384 // PHI node as operand #0, see if we can fold the instruction into the PHI
385 // (which is only possible if all operands to the PHI are constants).
386 Instruction *FoldOpIntoPhi(Instruction &I);
387
Chris Lattnerbac32862004-11-14 19:13:23 +0000388 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389 // operator and they all are only used by the PHI, PHI together their
390 // inputs, and do the operation once, to the result of the PHI.
391 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000392 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000393 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
394
Chris Lattner7da52b22006-11-01 04:51:18 +0000395
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000396 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
397 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000398
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000399 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000400 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000401 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000402 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000403 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000404 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000405 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000406 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000407 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000408
Chris Lattnerafe91a52006-06-15 19:07:26 +0000409
Reid Spencerc55b2432006-12-13 18:21:21 +0000410 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000411
Dan Gohman6de29f82009-06-15 22:12:54 +0000412 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000413 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000414 unsigned GetOrEnforceKnownAlignment(Value *V,
415 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000416
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000417 };
Chris Lattner873ff012009-08-30 05:55:36 +0000418} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000419
Dan Gohman844731a2008-05-13 00:00:25 +0000420char InstCombiner::ID = 0;
421static RegisterPass<InstCombiner>
422X("instcombine", "Combine redundant instructions");
423
Chris Lattner4f98c562003-03-10 21:43:22 +0000424// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000425// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000426static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000427 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000428 if (BinaryOperator::isNeg(V) ||
429 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000430 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000431 return 3;
432 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000433 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000434 if (isa<Argument>(V)) return 3;
435 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000436}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000437
Chris Lattnerc8802d22003-03-11 00:12:48 +0000438// isOnlyUse - Return true if this instruction will be deleted if we stop using
439// it.
440static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000441 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000442}
443
Chris Lattner4cb170c2004-02-23 06:38:22 +0000444// getPromotedType - Return the specified type promoted as it would be to pass
445// though a va_arg area...
446static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000447 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
448 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000449 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000450 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000451 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000452}
453
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000454/// getBitCastOperand - If the specified operand is a CastInst, a constant
455/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
456/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000457static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000458 if (Operator *O = dyn_cast<Operator>(V)) {
459 if (O->getOpcode() == Instruction::BitCast)
460 return O->getOperand(0);
461 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
462 if (GEP->hasAllZeroIndices())
463 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000464 }
Chris Lattnereed48272005-09-13 00:40:14 +0000465 return 0;
466}
467
Reid Spencer3da59db2006-11-27 01:05:10 +0000468/// This function is a wrapper around CastInst::isEliminableCastPair. It
469/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000470static Instruction::CastOps
471isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
476) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000477
Reid Spencer3da59db2006-11-27 01:05:10 +0000478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000480
Reid Spencer3da59db2006-11-27 01:05:10 +0000481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000484
Chris Lattnera0e69692009-03-24 18:35:40 +0000485 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000486 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000487 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000488
489 // We don't want to form an inttoptr or ptrtoint that converts to an integer
490 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000491 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000492 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000493 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000494 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000495 Res = 0;
496
497 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000498}
499
500/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501/// in any code being generated. It does not require codegen if V is simple
502/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000503static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
504 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000505 if (V->getType() == Ty || isa<Constant>(V)) return false;
506
Chris Lattner01575b72006-05-25 23:24:33 +0000507 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000508 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000509 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000510 return false;
511 return true;
512}
513
Chris Lattner4f98c562003-03-10 21:43:22 +0000514// SimplifyCommutative - This performs a few simplifications for commutative
515// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000516//
Chris Lattner4f98c562003-03-10 21:43:22 +0000517// 1. Order operands such that they are listed from right (least complex) to
518// left (most complex). This puts constants before unary operators before
519// binary operators.
520//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000521// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000523//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000524bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000525 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000526 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000527 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000528
Chris Lattner4f98c562003-03-10 21:43:22 +0000529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000534 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
539 return true;
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
545
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000547 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549 Op1->getOperand(0),
550 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000551 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
554 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000555 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000556 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000557 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000558}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000559
Reid Spencere4d87aa2006-12-23 06:05:41 +0000560/// SimplifyCompare - For a CmpInst this function just orders the operands
561/// so that theyare listed from right (least complex) to left (most complex).
562/// This puts constants before unary operators before binary operators.
563bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000564 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000565 return false;
566 I.swapOperands();
567 // Compare instructions are not associative so there's nothing else we can do.
568 return true;
569}
570
Chris Lattner8d969642003-03-10 23:06:50 +0000571// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
572// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000573//
Dan Gohman186a6362009-08-12 16:04:34 +0000574static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000575 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000576 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000577
Chris Lattner0ce85802004-12-14 20:08:06 +0000578 // Constants can be considered to be negated values if they can be folded.
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000580 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000581
582 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
583 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000584 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000585
Chris Lattner8d969642003-03-10 23:06:50 +0000586 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000587}
588
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000589// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
590// instruction if the LHS is a constant negative zero (which is the 'negate'
591// form).
592//
Dan Gohman186a6362009-08-12 16:04:34 +0000593static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000594 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000595 return BinaryOperator::getFNegArgument(V);
596
597 // Constants can be considered to be negated values if they can be folded.
598 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000599 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000600
601 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000603 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000604
605 return 0;
606}
607
Dan Gohman186a6362009-08-12 16:04:34 +0000608static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000609 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000610 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000611
612 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000613 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000614 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000615 return 0;
616}
617
Chris Lattnerc8802d22003-03-11 00:12:48 +0000618// dyn_castFoldableMul - If this value is a multiply that can be folded into
619// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000620// non-constant operand of the multiply, and set CST to point to the multiplier.
621// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000622//
Dan Gohman186a6362009-08-12 16:04:34 +0000623static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000624 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000625 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000626 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000627 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000628 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000629 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000630 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000631 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000632 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000633 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000634 CST = ConstantInt::get(V->getType()->getContext(),
635 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000636 return I->getOperand(0);
637 }
638 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000639 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000640}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000641
Reid Spencer7177c3a2007-03-25 05:33:51 +0000642/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000643static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000644 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000645 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000646}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000647/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000648static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000649 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000650 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000651}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000652/// MultiplyOverflows - True if the multiply can not be expressed in an int
653/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000654static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000655 uint32_t W = C1->getBitWidth();
656 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
657 if (sign) {
658 LHSExt.sext(W * 2);
659 RHSExt.sext(W * 2);
660 } else {
661 LHSExt.zext(W * 2);
662 RHSExt.zext(W * 2);
663 }
664
665 APInt MulExt = LHSExt * RHSExt;
666
667 if (sign) {
668 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670 return MulExt.slt(Min) || MulExt.sgt(Max);
671 } else
672 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
673}
Chris Lattner955f3312004-09-28 21:48:02 +0000674
Reid Spencere7816b52007-03-08 01:52:58 +0000675
Chris Lattner255d8912006-02-11 09:31:47 +0000676/// ShrinkDemandedConstant - Check to see if the specified operand of the
677/// specified instruction is a constant integer. If so, check to see if there
678/// are any bits set in the constant that are not demanded. If so, shrink the
679/// constant and return true.
680static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000681 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000682 assert(I && "No instruction?");
683 assert(OpNo < I->getNumOperands() && "Operand index too large");
684
685 // If the operand is not a constant integer, nothing to do.
686 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687 if (!OpC) return false;
688
689 // If there are no bits set that aren't demanded, nothing to do.
690 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691 if ((~Demanded & OpC->getValue()) == 0)
692 return false;
693
694 // This instruction is producing bits that are not demanded. Shrink the RHS.
695 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000696 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000697 return true;
698}
699
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000700// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
701// set of known zero and one bits, compute the maximum and minimum values that
702// could have the specified known zero and known one bits, returning them in
703// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000704static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000707 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708 KnownZero.getBitWidth() == Min.getBitWidth() &&
709 KnownZero.getBitWidth() == Max.getBitWidth() &&
710 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000711 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000712
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000713 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714 // bit if it is unknown.
715 Min = KnownOne;
716 Max = KnownOne|UnknownBits;
717
Dan Gohman1c8491e2009-04-25 17:12:48 +0000718 if (UnknownBits.isNegative()) { // Sign bit is unknown
719 Min.set(Min.getBitWidth()-1);
720 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000721 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000722}
723
724// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725// a set of known zero and one bits, compute the maximum and minimum values that
726// could have the specified known zero and known one bits, returning them in
727// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000728static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000734 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000735 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000736
737 // The minimum value is when the unknown bits are all zeros.
738 Min = KnownOne;
739 // The maximum value is when the unknown bits are all ones.
740 Max = KnownOne|UnknownBits;
741}
Chris Lattner255d8912006-02-11 09:31:47 +0000742
Chris Lattner886ab6c2009-01-31 08:15:18 +0000743/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744/// SimplifyDemandedBits knows about. See if the instruction has any
745/// properties that allow us to simplify its operands.
746bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000747 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000748 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
750
751 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
752 KnownZero, KnownOne, 0);
753 if (V == 0) return false;
754 if (V == &Inst) return true;
755 ReplaceInstUsesWith(Inst, V);
756 return true;
757}
758
759/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760/// specified instruction operand if possible, updating it in place. It returns
761/// true if it made any change and false otherwise.
762bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
763 APInt &KnownZero, APInt &KnownOne,
764 unsigned Depth) {
765 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766 KnownZero, KnownOne, Depth);
767 if (NewVal == 0) return false;
768 U.set(NewVal);
769 return true;
770}
771
772
773/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000775/// that only the bits set in DemandedMask of the result of V are ever used
776/// downstream. Consequently, depending on the mask and V, it may be possible
777/// to replace V with a constant or one of its operands. In such cases, this
778/// function does the replacement and returns true. In all other cases, it
779/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000780/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000781/// to be zero in the expression. These are provided to potentially allow the
782/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783/// the expression. KnownOne and KnownZero always follow the invariant that
784/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785/// the bits in KnownOne and KnownZero may only be accurate for those bits set
786/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000788///
789/// This returns null if it did not change anything and it permits no
790/// simplification. This returns V itself if it did some simplification of V's
791/// operands based on the information about what bits are demanded. This returns
792/// some other non-null value if it found out that V is equal to another value
793/// in the context where the specified bits are demanded, but not for all users.
794Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795 APInt &KnownZero, APInt &KnownOne,
796 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000797 assert(V != 0 && "Null pointer of Value???");
798 assert(Depth <= 6 && "Limit Search Depth");
799 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000800 const Type *VTy = V->getType();
801 assert((TD || !isa<PointerType>(VTy)) &&
802 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000803 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804 (!VTy->isIntOrIntVector() ||
805 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000806 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000807 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000808 "Value *V, DemandedMask, KnownZero and KnownOne "
809 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000810 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811 // We know all of the bits for a constant!
812 KnownOne = CI->getValue() & DemandedMask;
813 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000814 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000815 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000816 if (isa<ConstantPointerNull>(V)) {
817 // We know all of the bits for a constant!
818 KnownOne.clear();
819 KnownZero = DemandedMask;
820 return 0;
821 }
822
Chris Lattner08d2cc72009-01-31 07:26:06 +0000823 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000824 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000825 if (DemandedMask == 0) { // Not demanding any bits from V.
826 if (isa<UndefValue>(V))
827 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000828 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000829 }
830
Chris Lattner4598c942009-01-31 08:24:16 +0000831 if (Depth == 6) // Limit search depth.
832 return 0;
833
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000834 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
836
Dan Gohman1c8491e2009-04-25 17:12:48 +0000837 Instruction *I = dyn_cast<Instruction>(V);
838 if (!I) {
839 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840 return 0; // Only analyze instructions.
841 }
842
Chris Lattner4598c942009-01-31 08:24:16 +0000843 // If there are multiple uses of this value and we aren't at the root, then
844 // we can't do any simplifications of the operands, because DemandedMask
845 // only reflects the bits demanded by *one* of the users.
846 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000847 // Despite the fact that we can't simplify this instruction in all User's
848 // context, we can at least compute the knownzero/knownone bits, and we can
849 // do simplifications that apply to *just* the one user if we know that
850 // this instruction has a simpler value in that context.
851 if (I->getOpcode() == Instruction::And) {
852 // If either the LHS or the RHS are Zero, the result is zero.
853 ComputeMaskedBits(I->getOperand(1), DemandedMask,
854 RHSKnownZero, RHSKnownOne, Depth+1);
855 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856 LHSKnownZero, LHSKnownOne, Depth+1);
857
858 // If all of the demanded bits are known 1 on one side, return the other.
859 // These bits cannot contribute to the result of the 'and' in this
860 // context.
861 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
862 (DemandedMask & ~LHSKnownZero))
863 return I->getOperand(0);
864 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
865 (DemandedMask & ~RHSKnownZero))
866 return I->getOperand(1);
867
868 // If all of the demanded bits in the inputs are known zeros, return zero.
869 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000870 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000871
872 } else if (I->getOpcode() == Instruction::Or) {
873 // We can simplify (X|Y) -> X or Y in the user's context if we know that
874 // only bits from X or Y are demanded.
875
876 // If either the LHS or the RHS are One, the result is One.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
880 LHSKnownZero, LHSKnownOne, Depth+1);
881
882 // If all of the demanded bits are known zero on one side, return the
883 // other. These bits cannot contribute to the result of the 'or' in this
884 // context.
885 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
886 (DemandedMask & ~LHSKnownOne))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
889 (DemandedMask & ~RHSKnownOne))
890 return I->getOperand(1);
891
892 // If all of the potentially set bits on one side are known to be set on
893 // the other side, just use the 'other' side.
894 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
895 (DemandedMask & (~RHSKnownZero)))
896 return I->getOperand(0);
897 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
898 (DemandedMask & (~LHSKnownZero)))
899 return I->getOperand(1);
900 }
901
Chris Lattner4598c942009-01-31 08:24:16 +0000902 // Compute the KnownZero/KnownOne bits to simplify things downstream.
903 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
904 return 0;
905 }
906
907 // If this is the root being simplified, allow it to have multiple uses,
908 // just set the DemandedMask to all bits so that we can try to simplify the
909 // operands. This allows visitTruncInst (for example) to simplify the
910 // operand of a trunc without duplicating all the logic below.
911 if (Depth == 0 && !V->hasOneUse())
912 DemandedMask = APInt::getAllOnesValue(BitWidth);
913
Reid Spencer8cb68342007-03-12 17:25:59 +0000914 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000915 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000916 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000917 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000918 case Instruction::And:
919 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000920 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921 RHSKnownZero, RHSKnownOne, Depth+1) ||
922 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000923 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000924 return I;
925 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
926 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000927
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and'.
930 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
931 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000932 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000933 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
934 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000935 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000936
937 // If all of the demanded bits in the inputs are known zeros, return zero.
938 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000939 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000940
941 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000942 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000943 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000944
945 // Output known-1 bits are only known if set in both the LHS & RHS.
946 RHSKnownOne &= LHSKnownOne;
947 // Output known-0 are known to be clear if zero in either the LHS | RHS.
948 RHSKnownZero |= LHSKnownZero;
949 break;
950 case Instruction::Or:
951 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1) ||
954 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000955 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000956 return I;
957 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
958 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000959
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'or'.
962 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
963 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000964 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000965 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
966 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000967 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000968
969 // If all of the potentially set bits on one side are known to be set on
970 // the other side, just use the 'other' side.
971 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
972 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000973 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000974 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
975 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000977
978 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000980 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // Output known-0 bits are only known if clear in both the LHS & RHS.
983 RHSKnownZero &= LHSKnownZero;
984 // Output known-1 are known to be set if set in either the LHS | RHS.
985 RHSKnownOne |= LHSKnownOne;
986 break;
987 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +0000988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000991 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000992 return I;
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000995
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'xor'.
998 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +0000999 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001000 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001001 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001002
1003 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1005 (RHSKnownOne & LHSKnownOne);
1006 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1008 (RHSKnownOne & LHSKnownZero);
1009
1010 // If all of the demanded bits are known to be zero on one side or the
1011 // other, turn this into an *inclusive* or.
1012 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner74381062009-08-30 07:44:24 +00001013 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1014 return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
Reid Spencer8cb68342007-03-12 17:25:59 +00001015
1016 // If all of the demanded bits on one side are known, and all of the set
1017 // bits on that side are also known to be set on the other side, turn this
1018 // into an AND, as we know the bits will be cleared.
1019 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1020 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1021 // all known
1022 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001023 Constant *AndC = Constant::getIntegerValue(VTy,
1024 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001025 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001026 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 }
1029 }
1030
1031 // If the RHS is a constant, see if we can simplify it.
1032 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001033 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 RHSKnownZero = KnownZeroOut;
1037 RHSKnownOne = KnownOneOut;
1038 break;
1039 }
1040 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001041 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1042 RHSKnownZero, RHSKnownOne, Depth+1) ||
1043 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001044 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001045 return I;
1046 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1047 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001048
1049 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001050 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1051 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001052 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001053
1054 // Only known if known in both the LHS and RHS.
1055 RHSKnownOne &= LHSKnownOne;
1056 RHSKnownZero &= LHSKnownZero;
1057 break;
1058 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001059 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001060 DemandedMask.zext(truncBf);
1061 RHSKnownZero.zext(truncBf);
1062 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001063 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001064 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001066 DemandedMask.trunc(BitWidth);
1067 RHSKnownZero.trunc(BitWidth);
1068 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001070 break;
1071 }
1072 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001073 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001074 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001075
1076 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1077 if (const VectorType *SrcVTy =
1078 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1079 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1080 // Don't touch a bitcast between vectors of different element counts.
1081 return false;
1082 } else
1083 // Don't touch a scalar-to-vector bitcast.
1084 return false;
1085 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1086 // Don't touch a vector-to-scalar bitcast.
1087 return false;
1088
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001090 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001091 return I;
1092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001093 break;
1094 case Instruction::ZExt: {
1095 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001096 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001097
Zhou Shengd48653a2007-03-29 04:45:55 +00001098 DemandedMask.trunc(SrcBitWidth);
1099 RHSKnownZero.trunc(SrcBitWidth);
1100 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001101 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001102 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001103 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001104 DemandedMask.zext(BitWidth);
1105 RHSKnownZero.zext(BitWidth);
1106 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001107 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001108 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001109 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 break;
1111 }
1112 case Instruction::SExt: {
1113 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001114 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001115
Reid Spencer8cb68342007-03-12 17:25:59 +00001116 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001117 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001118
Zhou Sheng01542f32007-03-29 02:26:30 +00001119 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001120 // If any of the sign extended bits are demanded, we know that the sign
1121 // bit is demanded.
1122 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001123 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001124
Zhou Shengd48653a2007-03-29 04:45:55 +00001125 InputDemandedBits.trunc(SrcBitWidth);
1126 RHSKnownZero.trunc(SrcBitWidth);
1127 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001128 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001129 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001131 InputDemandedBits.zext(BitWidth);
1132 RHSKnownZero.zext(BitWidth);
1133 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001134 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001135
1136 // If the sign bit of the input is known set or clear, then we know the
1137 // top bits of the result.
1138
1139 // If the input sign bit is known zero, or if the NewBits are not demanded
1140 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001141 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001142 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001143 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1144 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001146 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001147 }
1148 break;
1149 }
1150 case Instruction::Add: {
1151 // Figure out what the input bits are. If the top bits of the and result
1152 // are not demanded, then the add doesn't demand them from its input
1153 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001155
1156 // If there is a constant on the RHS, there are a variety of xformations
1157 // we can do.
1158 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1159 // If null, this should be simplified elsewhere. Some of the xforms here
1160 // won't work if the RHS is zero.
1161 if (RHS->isZero())
1162 break;
1163
1164 // If the top bit of the output is demanded, demand everything from the
1165 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001166 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001167
1168 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001169 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001170 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001171 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001172
1173 // If the RHS of the add has bits set that can't affect the input, reduce
1174 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001175 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001177
1178 // Avoid excess work.
1179 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1180 break;
1181
1182 // Turn it into OR if input bits are zero.
1183 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1184 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001185 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001186 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001187 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 }
1189
1190 // We can say something about the output known-zero and known-one bits,
1191 // depending on potential carries from the input constant and the
1192 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1193 // bits set and the RHS constant is 0x01001, then we know we have a known
1194 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1195
1196 // To compute this, we first compute the potential carry bits. These are
1197 // the bits which may be modified. I'm not aware of a better way to do
1198 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001199 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001200 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001201
1202 // Now that we know which bits have carries, compute the known-1/0 sets.
1203
1204 // Bits are known one if they are known zero in one operand and one in the
1205 // other, and there is no input carry.
1206 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1207 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1208
1209 // Bits are known zero if they are known zero in both operands and there
1210 // is no input carry.
1211 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1212 } else {
1213 // If the high-bits of this ADD are not demanded, then it does not demand
1214 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001215 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 // Right fill the mask of bits for this ADD to demand the most
1217 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001218 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1220 LHSKnownZero, LHSKnownOne, Depth+1) ||
1221 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001223 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001224 }
1225 }
1226 break;
1227 }
1228 case Instruction::Sub:
1229 // If the high-bits of this SUB are not demanded, then it does not demand
1230 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001231 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 // Right fill the mask of bits for this SUB to demand the most
1233 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001234 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001235 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001236 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1237 LHSKnownZero, LHSKnownOne, Depth+1) ||
1238 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001239 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001240 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001241 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001242 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1243 // the known zeros and ones.
1244 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001245 break;
1246 case Instruction::Shl:
1247 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001248 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001249 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001250 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001251 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001252 return I;
1253 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001254 RHSKnownZero <<= ShiftAmt;
1255 RHSKnownOne <<= ShiftAmt;
1256 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001257 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001258 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 }
1260 break;
1261 case Instruction::LShr:
1262 // For a logical shift right
1263 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001264 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001265
Reid Spencer8cb68342007-03-12 17:25:59 +00001266 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001267 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001268 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001269 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 return I;
1271 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001272 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1273 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001274 if (ShiftAmt) {
1275 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001276 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001277 RHSKnownZero |= HighBits; // high bits known zero.
1278 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 }
1280 break;
1281 case Instruction::AShr:
1282 // If this is an arithmetic shift right and only the low-bit is set, we can
1283 // always convert this into a logical shr, even if the shift amount is
1284 // variable. The low bit of the shift cannot be an input sign bit unless
1285 // the shift amount is >= the size of the datatype, which is undefined.
1286 if (DemandedMask == 1) {
1287 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001288 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001289 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001291 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001292
1293 // If the sign bit is the only bit demanded by this ashr, then there is no
1294 // need to do it, the shift doesn't change the high bit.
1295 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001296 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001297
1298 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001299 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001300
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001302 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001303 // If any of the "high bits" are demanded, we should set the sign bit as
1304 // demanded.
1305 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1306 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001307 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001308 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001309 return I;
1310 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001312 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001313 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1314 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1315
1316 // Handle the sign bits.
1317 APInt SignBit(APInt::getSignBit(BitWidth));
1318 // Adjust to where it is now in the mask.
1319 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1320
1321 // If the input sign bit is known to be zero, or if none of the top bits
1322 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001323 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 (HighBits & ~DemandedMask) == HighBits) {
1325 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001326 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001327 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001328 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001329 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1330 RHSKnownOne |= HighBits;
1331 }
1332 }
1333 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001334 case Instruction::SRem:
1335 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001336 APInt RA = Rem->getValue().abs();
1337 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001338 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001339 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001340
Nick Lewycky8e394322008-11-02 02:41:50 +00001341 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001342 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001343 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001344 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001345 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001346
1347 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1348 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001349
1350 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001351
Chris Lattner886ab6c2009-01-31 08:15:18 +00001352 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001353 }
1354 }
1355 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001356 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001357 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1358 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1360 KnownZero2, KnownOne2, Depth+1) ||
1361 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001362 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001363 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001364
Chris Lattner455e9ab2009-01-21 18:09:24 +00001365 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001366 Leaders = std::max(Leaders,
1367 KnownZero2.countLeadingOnes());
1368 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001369 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001370 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001371 case Instruction::Call:
1372 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1373 switch (II->getIntrinsicID()) {
1374 default: break;
1375 case Intrinsic::bswap: {
1376 // If the only bits demanded come from one byte of the bswap result,
1377 // just shift the input byte into position to eliminate the bswap.
1378 unsigned NLZ = DemandedMask.countLeadingZeros();
1379 unsigned NTZ = DemandedMask.countTrailingZeros();
1380
1381 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1382 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1383 // have 14 leading zeros, round to 8.
1384 NLZ &= ~7;
1385 NTZ &= ~7;
1386 // If we need exactly one byte, we can do this transformation.
1387 if (BitWidth-NLZ-NTZ == 8) {
1388 unsigned ResultBit = NTZ;
1389 unsigned InputBit = BitWidth-NTZ-8;
1390
1391 // Replace this with either a left or right shift to get the byte into
1392 // the right place.
1393 Instruction *NewVal;
1394 if (InputBit > ResultBit)
1395 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001396 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001397 else
1398 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001399 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001400 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001401 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001402 }
1403
1404 // TODO: Could compute known zero/one bits based on the input.
1405 break;
1406 }
1407 }
1408 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001409 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001410 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001411 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001412
1413 // If the client is only demanding bits that we know, return the known
1414 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001415 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1416 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001417 return false;
1418}
1419
Chris Lattner867b99f2006-10-05 06:55:50 +00001420
Mon P Wangaeb06d22008-11-10 04:46:22 +00001421/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001422/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001423/// actually used by the caller. This method analyzes which elements of the
1424/// operand are undef and returns that information in UndefElts.
1425///
1426/// If the information about demanded elements can be used to simplify the
1427/// operation, the operation is simplified, then the resultant value is
1428/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001429Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1430 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001431 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001432 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001433 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001434 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001435
1436 if (isa<UndefValue>(V)) {
1437 // If the entire vector is undefined, just return this info.
1438 UndefElts = EltMask;
1439 return 0;
1440 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1441 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001442 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001443 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001444
Chris Lattner867b99f2006-10-05 06:55:50 +00001445 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001446 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1447 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001448 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001449
1450 std::vector<Constant*> Elts;
1451 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001452 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001453 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001454 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001455 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1456 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001457 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001458 } else { // Otherwise, defined.
1459 Elts.push_back(CP->getOperand(i));
1460 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001461
Chris Lattner867b99f2006-10-05 06:55:50 +00001462 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001463 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001464 return NewCP != CP ? NewCP : 0;
1465 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001466 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001467 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001468
1469 // Check if this is identity. If so, return 0 since we are not simplifying
1470 // anything.
1471 if (DemandedElts == ((1ULL << VWidth) -1))
1472 return 0;
1473
Reid Spencer9d6565a2007-02-15 02:26:10 +00001474 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001475 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001476 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001477 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001478 for (unsigned i = 0; i != VWidth; ++i) {
1479 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1480 Elts.push_back(Elt);
1481 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001483 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 }
1485
Dan Gohman488fbfc2008-09-09 18:11:14 +00001486 // Limit search depth.
1487 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001488 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001489
1490 // If multiple users are using the root value, procede with
1491 // simplification conservatively assuming that all elements
1492 // are needed.
1493 if (!V->hasOneUse()) {
1494 // Quit if we find multiple users of a non-root value though.
1495 // They'll be handled when it's their turn to be visited by
1496 // the main instcombine process.
1497 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001498 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001499 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001500
1501 // Conservatively assume that all elements are needed.
1502 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001503 }
1504
1505 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001506 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001507
1508 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001509 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001510 Value *TmpV;
1511 switch (I->getOpcode()) {
1512 default: break;
1513
1514 case Instruction::InsertElement: {
1515 // If this is a variable index, we don't know which element it overwrites.
1516 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001517 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 if (Idx == 0) {
1519 // Note that we can't propagate undef elt info, because we don't know
1520 // which elt is getting updated.
1521 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1522 UndefElts2, Depth+1);
1523 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1524 break;
1525 }
1526
1527 // If this is inserting an element that isn't demanded, remove this
1528 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001529 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001530 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1531 Worklist.Add(I);
1532 return I->getOperand(0);
1533 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001534
1535 // Otherwise, the element inserted overwrites whatever was there, so the
1536 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001537 APInt DemandedElts2 = DemandedElts;
1538 DemandedElts2.clear(IdxNo);
1539 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 UndefElts, Depth+1);
1541 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1542
1543 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001544 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001545 break;
1546 }
1547 case Instruction::ShuffleVector: {
1548 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001549 uint64_t LHSVWidth =
1550 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001551 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001552 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001553 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001554 unsigned MaskVal = Shuffle->getMaskValue(i);
1555 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001556 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001557 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001558 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001559 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001560 else
Evan Cheng388df622009-02-03 10:05:09 +00001561 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001562 }
1563 }
1564 }
1565
Nate Begeman7b254672009-02-11 22:36:25 +00001566 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001567 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001568 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001569 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1570
Nate Begeman7b254672009-02-11 22:36:25 +00001571 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1573 UndefElts3, Depth+1);
1574 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1575
1576 bool NewUndefElts = false;
1577 for (unsigned i = 0; i < VWidth; i++) {
1578 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001579 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001580 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001581 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001582 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001583 NewUndefElts = true;
1584 UndefElts.set(i);
1585 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001586 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001587 if (UndefElts3[MaskVal - LHSVWidth]) {
1588 NewUndefElts = true;
1589 UndefElts.set(i);
1590 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001591 }
1592 }
1593
1594 if (NewUndefElts) {
1595 // Add additional discovered undefs.
1596 std::vector<Constant*> Elts;
1597 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001598 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001599 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001600 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001601 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001602 Shuffle->getMaskValue(i)));
1603 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001604 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001605 MadeChange = true;
1606 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001607 break;
1608 }
Chris Lattner69878332007-04-14 22:29:23 +00001609 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001610 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001611 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1612 if (!VTy) break;
1613 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001614 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001615 unsigned Ratio;
1616
1617 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001618 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001619 // elements as are demanded of us.
1620 Ratio = 1;
1621 InputDemandedElts = DemandedElts;
1622 } else if (VWidth > InVWidth) {
1623 // Untested so far.
1624 break;
1625
1626 // If there are more elements in the result than there are in the source,
1627 // then an input element is live if any of the corresponding output
1628 // elements are live.
1629 Ratio = VWidth/InVWidth;
1630 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001631 if (DemandedElts[OutIdx])
1632 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001633 }
1634 } else {
1635 // Untested so far.
1636 break;
1637
1638 // If there are more elements in the source than there are in the result,
1639 // then an input element is live if the corresponding output element is
1640 // live.
1641 Ratio = InVWidth/VWidth;
1642 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001643 if (DemandedElts[InIdx/Ratio])
1644 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001645 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001646
Chris Lattner69878332007-04-14 22:29:23 +00001647 // div/rem demand all inputs, because they don't want divide by zero.
1648 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1649 UndefElts2, Depth+1);
1650 if (TmpV) {
1651 I->setOperand(0, TmpV);
1652 MadeChange = true;
1653 }
1654
1655 UndefElts = UndefElts2;
1656 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001657 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001658 // If there are more elements in the result than there are in the source,
1659 // then an output element is undef if the corresponding input element is
1660 // undef.
1661 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001662 if (UndefElts2[OutIdx/Ratio])
1663 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001664 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001665 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001666 // If there are more elements in the source than there are in the result,
1667 // then a result element is undef if all of the corresponding input
1668 // elements are undef.
1669 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1670 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001671 if (!UndefElts2[InIdx]) // Not undef?
1672 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001673 }
1674 break;
1675 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001676 case Instruction::And:
1677 case Instruction::Or:
1678 case Instruction::Xor:
1679 case Instruction::Add:
1680 case Instruction::Sub:
1681 case Instruction::Mul:
1682 // div/rem demand all inputs, because they don't want divide by zero.
1683 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1684 UndefElts, Depth+1);
1685 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1686 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1687 UndefElts2, Depth+1);
1688 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1689
1690 // Output elements are undefined if both are undefined. Consider things
1691 // like undef&0. The result is known zero, not undef.
1692 UndefElts &= UndefElts2;
1693 break;
1694
1695 case Instruction::Call: {
1696 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1697 if (!II) break;
1698 switch (II->getIntrinsicID()) {
1699 default: break;
1700
1701 // Binary vector operations that work column-wise. A dest element is a
1702 // function of the corresponding input elements from the two inputs.
1703 case Intrinsic::x86_sse_sub_ss:
1704 case Intrinsic::x86_sse_mul_ss:
1705 case Intrinsic::x86_sse_min_ss:
1706 case Intrinsic::x86_sse_max_ss:
1707 case Intrinsic::x86_sse2_sub_sd:
1708 case Intrinsic::x86_sse2_mul_sd:
1709 case Intrinsic::x86_sse2_min_sd:
1710 case Intrinsic::x86_sse2_max_sd:
1711 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1712 UndefElts, Depth+1);
1713 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1714 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1715 UndefElts2, Depth+1);
1716 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1717
1718 // If only the low elt is demanded and this is a scalarizable intrinsic,
1719 // scalarize it now.
1720 if (DemandedElts == 1) {
1721 switch (II->getIntrinsicID()) {
1722 default: break;
1723 case Intrinsic::x86_sse_sub_ss:
1724 case Intrinsic::x86_sse_mul_ss:
1725 case Intrinsic::x86_sse2_sub_sd:
1726 case Intrinsic::x86_sse2_mul_sd:
1727 // TODO: Lower MIN/MAX/ABS/etc
1728 Value *LHS = II->getOperand(1);
1729 Value *RHS = II->getOperand(2);
1730 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001731 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001732 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001733 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001734 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001735
1736 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001737 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001738 case Intrinsic::x86_sse_sub_ss:
1739 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001740 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001741 II->getName()), *II);
1742 break;
1743 case Intrinsic::x86_sse_mul_ss:
1744 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001745 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001746 II->getName()), *II);
1747 break;
1748 }
1749
1750 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001751 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001752 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001753 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001754 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001755 return New;
1756 }
1757 }
1758
1759 // Output elements are undefined if both are undefined. Consider things
1760 // like undef&0. The result is known zero, not undef.
1761 UndefElts &= UndefElts2;
1762 break;
1763 }
1764 break;
1765 }
1766 }
1767 return MadeChange ? I : 0;
1768}
1769
Dan Gohman45b4e482008-05-19 22:14:15 +00001770
Chris Lattner564a7272003-08-13 19:01:45 +00001771/// AssociativeOpt - Perform an optimization on an associative operator. This
1772/// function is designed to check a chain of associative operators for a
1773/// potential to apply a certain optimization. Since the optimization may be
1774/// applicable if the expression was reassociated, this checks the chain, then
1775/// reassociates the expression as necessary to expose the optimization
1776/// opportunity. This makes use of a special Functor, which must define
1777/// 'shouldApply' and 'apply' methods.
1778///
1779template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001780static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001781 unsigned Opcode = Root.getOpcode();
1782 Value *LHS = Root.getOperand(0);
1783
1784 // Quick check, see if the immediate LHS matches...
1785 if (F.shouldApply(LHS))
1786 return F.apply(Root);
1787
1788 // Otherwise, if the LHS is not of the same opcode as the root, return.
1789 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001790 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001791 // Should we apply this transform to the RHS?
1792 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1793
1794 // If not to the RHS, check to see if we should apply to the LHS...
1795 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1796 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1797 ShouldApply = true;
1798 }
1799
1800 // If the functor wants to apply the optimization to the RHS of LHSI,
1801 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1802 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001803 // Now all of the instructions are in the current basic block, go ahead
1804 // and perform the reassociation.
1805 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1806
1807 // First move the selected RHS to the LHS of the root...
1808 Root.setOperand(0, LHSI->getOperand(1));
1809
1810 // Make what used to be the LHS of the root be the user of the root...
1811 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001812 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001813 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001814 return 0;
1815 }
Chris Lattner65725312004-04-16 18:08:07 +00001816 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001817 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001818 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001819 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001820 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001821
1822 // Now propagate the ExtraOperand down the chain of instructions until we
1823 // get to LHSI.
1824 while (TmpLHSI != LHSI) {
1825 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001826 // Move the instruction to immediately before the chain we are
1827 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001828 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001829 ARI = NextLHSI;
1830
Chris Lattner564a7272003-08-13 19:01:45 +00001831 Value *NextOp = NextLHSI->getOperand(1);
1832 NextLHSI->setOperand(1, ExtraOperand);
1833 TmpLHSI = NextLHSI;
1834 ExtraOperand = NextOp;
1835 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001836
Chris Lattner564a7272003-08-13 19:01:45 +00001837 // Now that the instructions are reassociated, have the functor perform
1838 // the transformation...
1839 return F.apply(Root);
1840 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001841
Chris Lattner564a7272003-08-13 19:01:45 +00001842 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1843 }
1844 return 0;
1845}
1846
Dan Gohman844731a2008-05-13 00:00:25 +00001847namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001848
Nick Lewycky02d639f2008-05-23 04:34:58 +00001849// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001850struct AddRHS {
1851 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001852 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001853 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1854 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001855 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001856 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001857 }
1858};
1859
1860// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1861// iff C1&C2 == 0
1862struct AddMaskingAnd {
1863 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001864 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001865 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001866 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001867 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001868 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001869 }
1870 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001871 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001872 }
1873};
1874
Dan Gohman844731a2008-05-13 00:00:25 +00001875}
1876
Chris Lattner6e7ba452005-01-01 16:22:27 +00001877static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001878 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001879 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001880 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001881
Chris Lattner2eefe512004-04-09 19:05:30 +00001882 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001883 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1884 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001885
Chris Lattner2eefe512004-04-09 19:05:30 +00001886 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1887 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001888 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1889 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001890 }
1891
1892 Value *Op0 = SO, *Op1 = ConstOperand;
1893 if (!ConstIsRHS)
1894 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001895
Chris Lattner6e7ba452005-01-01 16:22:27 +00001896 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001897 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1898 SO->getName()+".op");
1899 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1900 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1901 SO->getName()+".cmp");
1902 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1903 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1904 SO->getName()+".cmp");
1905 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001906}
1907
1908// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1909// constant as the other operand, try to fold the binary operator into the
1910// select arguments. This also works for Cast instructions, which obviously do
1911// not have a second operand.
1912static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1913 InstCombiner *IC) {
1914 // Don't modify shared select instructions
1915 if (!SI->hasOneUse()) return 0;
1916 Value *TV = SI->getOperand(1);
1917 Value *FV = SI->getOperand(2);
1918
1919 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001920 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001921 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001922
Chris Lattner6e7ba452005-01-01 16:22:27 +00001923 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1924 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1925
Gabor Greif051a9502008-04-06 20:25:17 +00001926 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1927 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001928 }
1929 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001930}
1931
Chris Lattner4e998b22004-09-29 05:07:12 +00001932
1933/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1934/// node as operand #0, see if we can fold the instruction into the PHI (which
1935/// is only possible if all operands to the PHI are constants).
1936Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1937 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001938 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001939 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001940
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001941 // Check to see if all of the operands of the PHI are constants. If there is
1942 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001943 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001944 BasicBlock *NonConstBB = 0;
1945 for (unsigned i = 0; i != NumPHIValues; ++i)
1946 if (!isa<Constant>(PN->getIncomingValue(i))) {
1947 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001948 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001949 NonConstBB = PN->getIncomingBlock(i);
1950
1951 // If the incoming non-constant value is in I's block, we have an infinite
1952 // loop.
1953 if (NonConstBB == I.getParent())
1954 return 0;
1955 }
1956
1957 // If there is exactly one non-constant value, we can insert a copy of the
1958 // operation in that block. However, if this is a critical edge, we would be
1959 // inserting the computation one some other paths (e.g. inside a loop). Only
1960 // do this if the pred block is unconditionally branching into the phi block.
1961 if (NonConstBB) {
1962 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1963 if (!BI || !BI->isUnconditional()) return 0;
1964 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001965
1966 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001967 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001968 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001969 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001970 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001971
1972 // Next, add all of the operands to the PHI.
1973 if (I.getNumOperands() == 2) {
1974 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001975 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001976 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001977 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001978 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00001979 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001980 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00001981 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001982 } else {
1983 assert(PN->getIncomingBlock(i) == NonConstBB);
1984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001985 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001986 PN->getIncomingValue(i), C, "phitmp",
1987 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001988 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00001989 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00001990 CI->getPredicate(),
1991 PN->getIncomingValue(i), C, "phitmp",
1992 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001993 else
Torok Edwinc23197a2009-07-14 16:55:14 +00001994 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001995
Chris Lattner7a1e9242009-08-30 06:13:40 +00001996 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001997 }
1998 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001999 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002000 } else {
2001 CastInst *CI = cast<CastInst>(&I);
2002 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002003 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002004 Value *InV;
2005 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002006 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002007 } else {
2008 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002009 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002010 I.getType(), "phitmp",
2011 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002012 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002013 }
2014 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002015 }
2016 }
2017 return ReplaceInstUsesWith(I, NewPN);
2018}
2019
Chris Lattner2454a2e2008-01-29 06:52:45 +00002020
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002021/// WillNotOverflowSignedAdd - Return true if we can prove that:
2022/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2023/// This basically requires proving that the add in the original type would not
2024/// overflow to change the sign bit or have a carry out.
2025bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2026 // There are different heuristics we can use for this. Here are some simple
2027 // ones.
2028
2029 // Add has the property that adding any two 2's complement numbers can only
2030 // have one carry bit which can change a sign. As such, if LHS and RHS each
2031 // have at least two sign bits, we know that the addition of the two values will
2032 // sign extend fine.
2033 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2034 return true;
2035
2036
2037 // If one of the operands only has one non-zero bit, and if the other operand
2038 // has a known-zero bit in a more significant place than it (not including the
2039 // sign bit) the ripple may go up to and fill the zero, but won't change the
2040 // sign. For example, (X & ~4) + 1.
2041
2042 // TODO: Implement.
2043
2044 return false;
2045}
2046
Chris Lattner2454a2e2008-01-29 06:52:45 +00002047
Chris Lattner7e708292002-06-25 16:13:24 +00002048Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002049 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002050 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002051
Chris Lattner66331a42004-04-10 22:01:55 +00002052 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002053 // X + undef -> undef
2054 if (isa<UndefValue>(RHS))
2055 return ReplaceInstUsesWith(I, RHS);
2056
Chris Lattner66331a42004-04-10 22:01:55 +00002057 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002058 if (RHSC->isNullValue())
2059 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002060
Chris Lattner66331a42004-04-10 22:01:55 +00002061 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002062 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002063 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002064 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002065 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002066 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002067
2068 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2069 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002070 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002071 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002072
Eli Friedman709b33d2009-07-13 22:27:52 +00002073 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002074 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002075 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002076 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002077 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002078
2079 if (isa<PHINode>(LHS))
2080 if (Instruction *NV = FoldOpIntoPhi(I))
2081 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002082
Chris Lattner4f637d42006-01-06 17:59:59 +00002083 ConstantInt *XorRHS = 0;
2084 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002085 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002086 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002087 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002088 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002089
Zhou Sheng4351c642007-04-02 08:20:41 +00002090 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002091 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2092 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002093 do {
2094 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002095 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2096 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002097 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2098 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002099 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002100 if (!MaskedValueIsZero(XorLHS,
2101 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002102 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002103 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002104 }
2105 }
2106 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002107 C0080Val = APIntOps::lshr(C0080Val, Size);
2108 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2109 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002110
Reid Spencer35c38852007-03-28 01:36:16 +00002111 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002112 // with funny bit widths then this switch statement should be removed. It
2113 // is just here to get the size of the "middle" type back up to something
2114 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002115 const Type *MiddleType = 0;
2116 switch (Size) {
2117 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002118 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2119 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2120 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002121 }
2122 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002123 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002124 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002125 }
2126 }
Chris Lattner66331a42004-04-10 22:01:55 +00002127 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002128
Owen Anderson1d0be152009-08-13 21:58:54 +00002129 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002130 return BinaryOperator::CreateXor(LHS, RHS);
2131
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002132 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002133 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002134 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002135 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002136
2137 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2138 if (RHSI->getOpcode() == Instruction::Sub)
2139 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2140 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2141 }
2142 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2143 if (LHSI->getOpcode() == Instruction::Sub)
2144 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2145 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2146 }
Robert Bocchino71698282004-07-27 21:02:21 +00002147 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002148
Chris Lattner5c4afb92002-05-08 22:46:53 +00002149 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002150 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002151 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002152 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002153 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002154 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002155 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002156 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002157 }
2158
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002159 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002160 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002161
2162 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002163 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002164 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002165 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002166
Misha Brukmanfd939082005-04-21 23:48:37 +00002167
Chris Lattner50af16a2004-11-13 19:50:12 +00002168 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002169 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002170 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002171 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002172
2173 // X*C1 + X*C2 --> X * (C1+C2)
2174 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002175 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002176 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002177 }
2178
2179 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002180 if (dyn_castFoldableMul(RHS, C2) == LHS)
2181 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002182
Chris Lattnere617c9e2007-01-05 02:17:46 +00002183 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002184 if (dyn_castNotVal(LHS) == RHS ||
2185 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002186 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002187
Chris Lattnerad3448c2003-02-18 19:57:07 +00002188
Chris Lattner564a7272003-08-13 19:01:45 +00002189 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002190 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2191 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002192 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002193
2194 // A+B --> A|B iff A and B have no bits set in common.
2195 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2196 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2197 APInt LHSKnownOne(IT->getBitWidth(), 0);
2198 APInt LHSKnownZero(IT->getBitWidth(), 0);
2199 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2200 if (LHSKnownZero != 0) {
2201 APInt RHSKnownOne(IT->getBitWidth(), 0);
2202 APInt RHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2204
2205 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002206 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002207 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002208 }
2209 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002210
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002211 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002212 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002213 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002214 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2215 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002216 if (W != Y) {
2217 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002218 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002219 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002220 std::swap(W, X);
2221 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002222 std::swap(Y, Z);
2223 std::swap(W, X);
2224 }
2225 }
2226
2227 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002228 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002229 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002230 }
2231 }
2232 }
2233
Chris Lattner6b032052003-10-02 15:11:26 +00002234 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002235 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002236 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002237 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002238
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002239 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002240 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002241 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002242 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002243 if (Anded == CRHS) {
2244 // See if all bits from the first bit set in the Add RHS up are included
2245 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002246 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002247
2248 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002249 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002250
2251 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002252 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002253
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002254 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2255 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002256 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002257 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002258 }
2259 }
2260 }
2261
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002262 // Try to fold constant add into select arguments.
2263 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002264 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002265 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002266 }
2267
Chris Lattner42790482007-12-20 01:56:58 +00002268 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002269 {
2270 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002271 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002272 if (!SI) {
2273 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002274 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002275 }
Chris Lattner42790482007-12-20 01:56:58 +00002276 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002277 Value *TV = SI->getTrueValue();
2278 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002279 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002280
2281 // Can we fold the add into the argument of the select?
2282 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002283 if (match(FV, m_Zero()) &&
2284 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002285 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002286 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002287 if (match(TV, m_Zero()) &&
2288 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002289 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002290 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002291 }
2292 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002293
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002294 // Check for (add (sext x), y), see if we can merge this into an
2295 // integer add followed by a sext.
2296 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2297 // (add (sext x), cst) --> (sext (add x, cst'))
2298 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2299 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002300 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002301 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002302 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002305 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2306 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002307 return new SExtInst(NewAdd, I.getType());
2308 }
2309 }
2310
2311 // (add (sext x), (sext y)) --> (sext (add int x, y))
2312 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2313 // Only do this if x/y have the same type, if at last one of them has a
2314 // single use (so we don't increase the number of sexts), and if the
2315 // integer add will not overflow.
2316 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2317 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2318 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2319 RHSConv->getOperand(0))) {
2320 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002321 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2322 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002323 return new SExtInst(NewAdd, I.getType());
2324 }
2325 }
2326 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002327
2328 return Changed ? &I : 0;
2329}
2330
2331Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2332 bool Changed = SimplifyCommutative(I);
2333 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2334
2335 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2336 // X + 0 --> X
2337 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002338 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002339 (I.getType())->getValueAPF()))
2340 return ReplaceInstUsesWith(I, LHS);
2341 }
2342
2343 if (isa<PHINode>(LHS))
2344 if (Instruction *NV = FoldOpIntoPhi(I))
2345 return NV;
2346 }
2347
2348 // -A + B --> B - A
2349 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002350 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002351 return BinaryOperator::CreateFSub(RHS, LHSV);
2352
2353 // A + -B --> A - B
2354 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002355 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002356 return BinaryOperator::CreateFSub(LHS, V);
2357
2358 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2359 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2360 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2361 return ReplaceInstUsesWith(I, LHS);
2362
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002363 // Check for (add double (sitofp x), y), see if we can merge this into an
2364 // integer add followed by a promotion.
2365 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2366 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2367 // ... if the constant fits in the integer value. This is useful for things
2368 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2369 // requires a constant pool load, and generally allows the add to be better
2370 // instcombined.
2371 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2372 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002373 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002374 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002375 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002376 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2377 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002378 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2379 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002380 return new SIToFPInst(NewAdd, I.getType());
2381 }
2382 }
2383
2384 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2385 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2386 // Only do this if x/y have the same type, if at last one of them has a
2387 // single use (so we don't increase the number of int->fp conversions),
2388 // and if the integer add will not overflow.
2389 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2390 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2391 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2392 RHSConv->getOperand(0))) {
2393 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002394 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2395 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002396 return new SIToFPInst(NewAdd, I.getType());
2397 }
2398 }
2399 }
2400
Chris Lattner7e708292002-06-25 16:13:24 +00002401 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002402}
2403
Chris Lattner7e708292002-06-25 16:13:24 +00002404Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002405 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002406
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002407 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002408 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002409
Chris Lattner233f7dc2002-08-12 21:17:25 +00002410 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002411 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002412 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002413
Chris Lattnere87597f2004-10-16 18:11:37 +00002414 if (isa<UndefValue>(Op0))
2415 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2416 if (isa<UndefValue>(Op1))
2417 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2418
Chris Lattnerd65460f2003-11-05 01:06:05 +00002419 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2420 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002421 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002422 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002423
Chris Lattnerd65460f2003-11-05 01:06:05 +00002424 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002425 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002426 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002427 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002428
Chris Lattner76b7a062007-01-15 07:02:54 +00002429 // -(X >>u 31) -> (X >>s 31)
2430 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002431 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002432 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002433 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002434 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002435 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002436 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002437 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002438 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002439 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002440 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002441 }
2442 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002443 }
2444 else if (SI->getOpcode() == Instruction::AShr) {
2445 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2446 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002447 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002448 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002449 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002450 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002451 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002452 }
2453 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002454 }
2455 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002456 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002457
2458 // Try to fold constant sub into select arguments.
2459 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002460 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002461 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002462
2463 // C - zext(bool) -> bool ? C - 1 : C
2464 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002465 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002466 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002467 }
2468
Owen Anderson1d0be152009-08-13 21:58:54 +00002469 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002470 return BinaryOperator::CreateXor(Op0, Op1);
2471
Chris Lattner43d84d62005-04-07 16:15:25 +00002472 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002473 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002474 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002475 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002476 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002477 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002478 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002479 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002480 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2481 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2482 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002483 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002484 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002485 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002486 }
2487
Chris Lattnerfd059242003-10-15 16:48:29 +00002488 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002489 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2490 // is not used by anyone else...
2491 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002492 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002493 // Swap the two operands of the subexpr...
2494 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2495 Op1I->setOperand(0, IIOp1);
2496 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002497
Chris Lattnera2881962003-02-18 19:28:33 +00002498 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002499 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002500 }
2501
2502 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2503 //
2504 if (Op1I->getOpcode() == Instruction::And &&
2505 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2506 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2507
Chris Lattner74381062009-08-30 07:44:24 +00002508 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002509 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002510 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002511
Reid Spencerac5209e2006-10-16 23:08:08 +00002512 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002513 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002514 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002515 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002516 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002517 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002518 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002519
Chris Lattnerad3448c2003-02-18 19:57:07 +00002520 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002521 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002522 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002523 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002524 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002525 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002527 }
Chris Lattner40371712002-05-09 01:29:19 +00002528 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002529 }
Chris Lattnera2881962003-02-18 19:28:33 +00002530
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002531 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2532 if (Op0I->getOpcode() == Instruction::Add) {
2533 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2534 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2535 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2536 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2537 } else if (Op0I->getOpcode() == Instruction::Sub) {
2538 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002539 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002540 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002541 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002542 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002543
Chris Lattner50af16a2004-11-13 19:50:12 +00002544 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002545 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002546 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002547 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002548
Chris Lattner50af16a2004-11-13 19:50:12 +00002549 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002550 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002551 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002552 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002553 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002554}
2555
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002556Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2557 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2558
2559 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002560 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002561 return BinaryOperator::CreateFAdd(Op0, V);
2562
2563 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2564 if (Op1I->getOpcode() == Instruction::FAdd) {
2565 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002566 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002567 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002568 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002569 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002570 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002571 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002572 }
2573
2574 return 0;
2575}
2576
Chris Lattnera0141b92007-07-15 20:42:37 +00002577/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2578/// comparison only checks the sign bit. If it only checks the sign bit, set
2579/// TrueIfSigned if the result of the comparison is true when the input value is
2580/// signed.
2581static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2582 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002583 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002584 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2585 TrueIfSigned = true;
2586 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002587 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2588 TrueIfSigned = true;
2589 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002590 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2591 TrueIfSigned = false;
2592 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002593 case ICmpInst::ICMP_UGT:
2594 // True if LHS u> RHS and RHS == high-bit-mask - 1
2595 TrueIfSigned = true;
2596 return RHS->getValue() ==
2597 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2598 case ICmpInst::ICMP_UGE:
2599 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2600 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002601 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002602 default:
2603 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002604 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002605}
2606
Chris Lattner7e708292002-06-25 16:13:24 +00002607Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002608 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002609 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002610
Eli Friedman1694e092009-07-18 09:12:15 +00002611 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002612 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002613
Chris Lattner233f7dc2002-08-12 21:17:25 +00002614 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002615 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002617
2618 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002619 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002620 if (SI->getOpcode() == Instruction::Shl)
2621 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002622 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002623 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002624
Zhou Sheng843f07672007-04-19 05:39:12 +00002625 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002626 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2627 if (CI->equalsInt(1)) // X * 1 == X
2628 return ReplaceInstUsesWith(I, Op0);
2629 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002630 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002631
Zhou Sheng97b52c22007-03-29 01:57:21 +00002632 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002633 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002634 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002635 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002636 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002637 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002638 if (Op1->isNullValue())
2639 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002640
2641 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2642 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002643 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002644
2645 // As above, vector X*splat(1.0) -> X in all defined cases.
2646 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002647 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2648 if (CI->equalsInt(1))
2649 return ReplaceInstUsesWith(I, Op0);
2650 }
2651 }
Chris Lattnera2881962003-02-18 19:28:33 +00002652 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002653
2654 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2655 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002656 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002657 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002658 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2659 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002660 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002661
2662 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002663
2664 // Try to fold constant mul into select arguments.
2665 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002666 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002667 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002668
2669 if (isa<PHINode>(Op0))
2670 if (Instruction *NV = FoldOpIntoPhi(I))
2671 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002672 }
2673
Dan Gohman186a6362009-08-12 16:04:34 +00002674 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2675 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002676 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002677
Nick Lewycky0c730792008-11-21 07:33:58 +00002678 // (X / Y) * Y = X - (X % Y)
2679 // (X / Y) * -Y = (X % Y) - X
2680 {
2681 Value *Op1 = I.getOperand(1);
2682 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2683 if (!BO ||
2684 (BO->getOpcode() != Instruction::UDiv &&
2685 BO->getOpcode() != Instruction::SDiv)) {
2686 Op1 = Op0;
2687 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2688 }
Dan Gohman186a6362009-08-12 16:04:34 +00002689 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002690 if (BO && BO->hasOneUse() &&
2691 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2692 (BO->getOpcode() == Instruction::UDiv ||
2693 BO->getOpcode() == Instruction::SDiv)) {
2694 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2695
Dan Gohmanfa94b942009-08-12 16:33:09 +00002696 // If the division is exact, X % Y is zero.
2697 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2698 if (SDiv->isExact()) {
2699 if (Op1BO == Op1)
2700 return ReplaceInstUsesWith(I, Op0BO);
2701 else
2702 return BinaryOperator::CreateNeg(Op0BO);
2703 }
2704
Chris Lattner74381062009-08-30 07:44:24 +00002705 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002706 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002707 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002708 else
Chris Lattner74381062009-08-30 07:44:24 +00002709 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002710 Rem->takeName(BO);
2711
2712 if (Op1BO == Op1)
2713 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002714 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002715 }
2716 }
2717
Owen Anderson1d0be152009-08-13 21:58:54 +00002718 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002719 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2720
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002721 // If one of the operands of the multiply is a cast from a boolean value, then
2722 // we know the bool is either zero or one, so this is a 'masking' multiply.
2723 // See if we can simplify things based on how the boolean was originally
2724 // formed.
2725 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002726 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002727 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002728 BoolCast = CI;
2729 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002730 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002731 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002732 BoolCast = CI;
2733 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002734 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002735 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2736 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002737 bool TIS = false;
2738
Reid Spencere4d87aa2006-12-23 06:05:41 +00002739 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002740 // multiply into a shift/and combination.
2741 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002742 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2743 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002744 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002745 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002746 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002747 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2748 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002749
2750 // If the multiply type is not the same as the source type, sign extend
2751 // or truncate to the multiply type.
Chris Lattner2345d1d2009-08-30 20:01:10 +00002752 if (I.getType() != V->getType())
2753 V = Builder->CreateIntCast(V, I.getType(), true);
Misha Brukmanfd939082005-04-21 23:48:37 +00002754
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002755 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002756 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002757 }
2758 }
2759 }
2760
Chris Lattner7e708292002-06-25 16:13:24 +00002761 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002762}
2763
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002764Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2765 bool Changed = SimplifyCommutative(I);
2766 Value *Op0 = I.getOperand(0);
2767
2768 // Simplify mul instructions with a constant RHS...
2769 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2770 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2771 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2772 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2773 if (Op1F->isExactlyValue(1.0))
2774 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2775 } else if (isa<VectorType>(Op1->getType())) {
2776 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2777 // As above, vector X*splat(1.0) -> X in all defined cases.
2778 if (Constant *Splat = Op1V->getSplatValue()) {
2779 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2780 if (F->isExactlyValue(1.0))
2781 return ReplaceInstUsesWith(I, Op0);
2782 }
2783 }
2784 }
2785
2786 // Try to fold constant mul into select arguments.
2787 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2788 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2789 return R;
2790
2791 if (isa<PHINode>(Op0))
2792 if (Instruction *NV = FoldOpIntoPhi(I))
2793 return NV;
2794 }
2795
Dan Gohman186a6362009-08-12 16:04:34 +00002796 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2797 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002798 return BinaryOperator::CreateFMul(Op0v, Op1v);
2799
2800 return Changed ? &I : 0;
2801}
2802
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002803/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2804/// instruction.
2805bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2806 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2807
2808 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2809 int NonNullOperand = -1;
2810 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2811 if (ST->isNullValue())
2812 NonNullOperand = 2;
2813 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2814 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2815 if (ST->isNullValue())
2816 NonNullOperand = 1;
2817
2818 if (NonNullOperand == -1)
2819 return false;
2820
2821 Value *SelectCond = SI->getOperand(0);
2822
2823 // Change the div/rem to use 'Y' instead of the select.
2824 I.setOperand(1, SI->getOperand(NonNullOperand));
2825
2826 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2827 // problem. However, the select, or the condition of the select may have
2828 // multiple uses. Based on our knowledge that the operand must be non-zero,
2829 // propagate the known value for the select into other uses of it, and
2830 // propagate a known value of the condition into its other users.
2831
2832 // If the select and condition only have a single use, don't bother with this,
2833 // early exit.
2834 if (SI->use_empty() && SelectCond->hasOneUse())
2835 return true;
2836
2837 // Scan the current block backward, looking for other uses of SI.
2838 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2839
2840 while (BBI != BBFront) {
2841 --BBI;
2842 // If we found a call to a function, we can't assume it will return, so
2843 // information from below it cannot be propagated above it.
2844 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2845 break;
2846
2847 // Replace uses of the select or its condition with the known values.
2848 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2849 I != E; ++I) {
2850 if (*I == SI) {
2851 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002852 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002853 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002854 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2855 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002856 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002857 }
2858 }
2859
2860 // If we past the instruction, quit looking for it.
2861 if (&*BBI == SI)
2862 SI = 0;
2863 if (&*BBI == SelectCond)
2864 SelectCond = 0;
2865
2866 // If we ran out of things to eliminate, break out of the loop.
2867 if (SelectCond == 0 && SI == 0)
2868 break;
2869
2870 }
2871 return true;
2872}
2873
2874
Reid Spencer1628cec2006-10-26 06:15:43 +00002875/// This function implements the transforms on div instructions that work
2876/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2877/// used by the visitors to those instructions.
2878/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002879Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002881
Chris Lattner50b2ca42008-02-19 06:12:18 +00002882 // undef / X -> 0 for integer.
2883 // undef / X -> undef for FP (the undef could be a snan).
2884 if (isa<UndefValue>(Op0)) {
2885 if (Op0->getType()->isFPOrFPVector())
2886 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002888 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002889
2890 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002891 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002892 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002893
Reid Spencer1628cec2006-10-26 06:15:43 +00002894 return 0;
2895}
Misha Brukmanfd939082005-04-21 23:48:37 +00002896
Reid Spencer1628cec2006-10-26 06:15:43 +00002897/// This function implements the transforms common to both integer division
2898/// instructions (udiv and sdiv). It is called by the visitors to those integer
2899/// division instructions.
2900/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002901Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2903
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002904 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002905 if (Op0 == Op1) {
2906 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002907 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002908 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002909 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002910 }
2911
Owen Andersoneed707b2009-07-24 23:12:02 +00002912 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002913 return ReplaceInstUsesWith(I, CI);
2914 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002915
Reid Spencer1628cec2006-10-26 06:15:43 +00002916 if (Instruction *Common = commonDivTransforms(I))
2917 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002918
2919 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2920 // This does not apply for fdiv.
2921 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2922 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002923
2924 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2925 // div X, 1 == X
2926 if (RHS->equalsInt(1))
2927 return ReplaceInstUsesWith(I, Op0);
2928
2929 // (X / C1) / C2 -> X / (C1*C2)
2930 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2931 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2932 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002933 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002934 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002936 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002937 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002938 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002939 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002940
Reid Spencerbca0e382007-03-23 20:05:17 +00002941 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002942 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2943 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2944 return R;
2945 if (isa<PHINode>(Op0))
2946 if (Instruction *NV = FoldOpIntoPhi(I))
2947 return NV;
2948 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002949 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002950
Chris Lattnera2881962003-02-18 19:28:33 +00002951 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002952 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002953 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002955
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002956 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002957 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002958 return ReplaceInstUsesWith(I, Op0);
2959
Nick Lewycky895f0852008-11-27 20:21:08 +00002960 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2961 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2962 // div X, 1 == X
2963 if (X->isOne())
2964 return ReplaceInstUsesWith(I, Op0);
2965 }
2966
Reid Spencer1628cec2006-10-26 06:15:43 +00002967 return 0;
2968}
2969
2970Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2972
2973 // Handle the integer div common cases
2974 if (Instruction *Common = commonIDivTransforms(I))
2975 return Common;
2976
Reid Spencer1628cec2006-10-26 06:15:43 +00002977 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00002978 // X udiv C^2 -> X >> C
2979 // Check to see if this is an unsigned division with an exact power of 2,
2980 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00002981 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002982 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002983 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002984
2985 // X udiv C, where C >= signbit
2986 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00002987 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00002988 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00002989 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00002990 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002991 }
2992
2993 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002994 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002995 if (RHSI->getOpcode() == Instruction::Shl &&
2996 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002997 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002998 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002999 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003000 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003001 if (uint32_t C2 = C1.logBase2())
3002 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003003 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003004 }
3005 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003006 }
3007
Reid Spencer1628cec2006-10-26 06:15:43 +00003008 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3009 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003010 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003011 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003012 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003013 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003014 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003015 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003016 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003017 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003018 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003019 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003020
3021 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003022 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003023 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003024
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003025 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003026 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003027 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003028 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003029 return 0;
3030}
3031
Reid Spencer1628cec2006-10-26 06:15:43 +00003032Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3033 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3034
3035 // Handle the integer div common cases
3036 if (Instruction *Common = commonIDivTransforms(I))
3037 return Common;
3038
3039 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3040 // sdiv X, -1 == -X
3041 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003042 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003043
Dan Gohmanfa94b942009-08-12 16:33:09 +00003044 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003045 if (cast<SDivOperator>(&I)->isExact() &&
3046 RHS->getValue().isNonNegative() &&
3047 RHS->getValue().isPowerOf2()) {
3048 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3049 RHS->getValue().exactLogBase2());
3050 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3051 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003052
3053 // -X/C --> X/-C provided the negation doesn't overflow.
3054 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3055 if (isa<Constant>(Sub->getOperand(0)) &&
3056 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003057 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003058 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3059 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003060 }
3061
3062 // If the sign bits of both operands are zero (i.e. we can prove they are
3063 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003064 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003065 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003066 if (MaskedValueIsZero(Op0, Mask)) {
3067 if (MaskedValueIsZero(Op1, Mask)) {
3068 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3069 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3070 }
3071 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003072 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003073 ShiftedInt->getValue().isPowerOf2()) {
3074 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3075 // Safe because the only negative value (1 << Y) can take on is
3076 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3077 // the sign bit set.
3078 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3079 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003080 }
Eli Friedman8be17392009-07-18 09:53:21 +00003081 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003082
3083 return 0;
3084}
3085
3086Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3087 return commonDivTransforms(I);
3088}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003089
Reid Spencer0a783f72006-11-02 01:53:59 +00003090/// This function implements the transforms on rem instructions that work
3091/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3092/// is used by the visitors to those instructions.
3093/// @brief Transforms common to all three rem instructions
3094Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003095 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003096
Chris Lattner50b2ca42008-02-19 06:12:18 +00003097 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3098 if (I.getType()->isFPOrFPVector())
3099 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003100 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003101 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003102 if (isa<UndefValue>(Op1))
3103 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003104
3105 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003106 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3107 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003108
Reid Spencer0a783f72006-11-02 01:53:59 +00003109 return 0;
3110}
3111
3112/// This function implements the transforms common to both integer remainder
3113/// instructions (urem and srem). It is called by the visitors to those integer
3114/// remainder instructions.
3115/// @brief Common integer remainder transforms
3116Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3117 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3118
3119 if (Instruction *common = commonRemTransforms(I))
3120 return common;
3121
Dale Johannesened6af242009-01-21 00:35:19 +00003122 // 0 % X == 0 for integer, we don't need to preserve faults!
3123 if (Constant *LHS = dyn_cast<Constant>(Op0))
3124 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003126
Chris Lattner857e8cd2004-12-12 21:48:58 +00003127 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003128 // X % 0 == undef, we don't need to preserve faults!
3129 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003130 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003131
Chris Lattnera2881962003-02-18 19:28:33 +00003132 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003133 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003134
Chris Lattner97943922006-02-28 05:49:21 +00003135 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3136 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3137 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3138 return R;
3139 } else if (isa<PHINode>(Op0I)) {
3140 if (Instruction *NV = FoldOpIntoPhi(I))
3141 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003142 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003143
3144 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003145 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003146 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003147 }
Chris Lattnera2881962003-02-18 19:28:33 +00003148 }
3149
Reid Spencer0a783f72006-11-02 01:53:59 +00003150 return 0;
3151}
3152
3153Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3154 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3155
3156 if (Instruction *common = commonIRemTransforms(I))
3157 return common;
3158
3159 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3160 // X urem C^2 -> X and C
3161 // Check to see if this is an unsigned remainder with an exact power of 2,
3162 // if so, convert to a bitwise and.
3163 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003164 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003165 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003166 }
3167
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003168 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003169 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3170 if (RHSI->getOpcode() == Instruction::Shl &&
3171 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003172 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003173 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003174 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003175 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003176 }
3177 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003178 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003179
Reid Spencer0a783f72006-11-02 01:53:59 +00003180 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3181 // where C1&C2 are powers of two.
3182 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3183 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3184 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3185 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003186 if ((STO->getValue().isPowerOf2()) &&
3187 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003188 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3189 SI->getName()+".t");
3190 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3191 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003192 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003193 }
3194 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003195 }
3196
Chris Lattner3f5b8772002-05-06 16:14:14 +00003197 return 0;
3198}
3199
Reid Spencer0a783f72006-11-02 01:53:59 +00003200Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3201 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3202
Dan Gohmancff55092007-11-05 23:16:33 +00003203 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003204 if (Instruction *Common = commonIRemTransforms(I))
3205 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003206
Dan Gohman186a6362009-08-12 16:04:34 +00003207 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003208 if (!isa<Constant>(RHSNeg) ||
3209 (isa<ConstantInt>(RHSNeg) &&
3210 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003211 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003212 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003213 I.setOperand(1, RHSNeg);
3214 return &I;
3215 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003216
Dan Gohmancff55092007-11-05 23:16:33 +00003217 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003218 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003219 if (I.getType()->isInteger()) {
3220 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3221 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3222 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003223 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003224 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003225 }
3226
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003227 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003228 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3229 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003230
Nick Lewycky9dce8732008-12-20 16:48:00 +00003231 bool hasNegative = false;
3232 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3233 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3234 if (RHS->getValue().isNegative())
3235 hasNegative = true;
3236
3237 if (hasNegative) {
3238 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003239 for (unsigned i = 0; i != VWidth; ++i) {
3240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3241 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003242 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003243 else
3244 Elts[i] = RHS;
3245 }
3246 }
3247
Owen Andersonaf7ec972009-07-28 21:19:26 +00003248 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003249 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003250 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003251 I.setOperand(1, NewRHSV);
3252 return &I;
3253 }
3254 }
3255 }
3256
Reid Spencer0a783f72006-11-02 01:53:59 +00003257 return 0;
3258}
3259
3260Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003261 return commonRemTransforms(I);
3262}
3263
Chris Lattner457dd822004-06-09 07:59:58 +00003264// isOneBitSet - Return true if there is exactly one bit set in the specified
3265// constant.
3266static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003267 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003268}
3269
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003270// isHighOnes - Return true if the constant is of the form 1+0+.
3271// This is the same as lowones(~X).
3272static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003273 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003274}
3275
Reid Spencere4d87aa2006-12-23 06:05:41 +00003276/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003277/// are carefully arranged to allow folding of expressions such as:
3278///
3279/// (A < B) | (A > B) --> (A != B)
3280///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003281/// Note that this is only valid if the first and second predicates have the
3282/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003283///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003284/// Three bits are used to represent the condition, as follows:
3285/// 0 A > B
3286/// 1 A == B
3287/// 2 A < B
3288///
3289/// <=> Value Definition
3290/// 000 0 Always false
3291/// 001 1 A > B
3292/// 010 2 A == B
3293/// 011 3 A >= B
3294/// 100 4 A < B
3295/// 101 5 A != B
3296/// 110 6 A <= B
3297/// 111 7 Always true
3298///
3299static unsigned getICmpCode(const ICmpInst *ICI) {
3300 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003301 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003302 case ICmpInst::ICMP_UGT: return 1; // 001
3303 case ICmpInst::ICMP_SGT: return 1; // 001
3304 case ICmpInst::ICMP_EQ: return 2; // 010
3305 case ICmpInst::ICMP_UGE: return 3; // 011
3306 case ICmpInst::ICMP_SGE: return 3; // 011
3307 case ICmpInst::ICMP_ULT: return 4; // 100
3308 case ICmpInst::ICMP_SLT: return 4; // 100
3309 case ICmpInst::ICMP_NE: return 5; // 101
3310 case ICmpInst::ICMP_ULE: return 6; // 110
3311 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003312 // True -> 7
3313 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003314 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003315 return 0;
3316 }
3317}
3318
Evan Cheng8db90722008-10-14 17:15:11 +00003319/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3320/// predicate into a three bit mask. It also returns whether it is an ordered
3321/// predicate by reference.
3322static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3323 isOrdered = false;
3324 switch (CC) {
3325 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3326 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003327 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3328 case FCmpInst::FCMP_UGT: return 1; // 001
3329 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3330 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003331 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3332 case FCmpInst::FCMP_UGE: return 3; // 011
3333 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3334 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003335 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3336 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003337 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3338 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003339 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003340 default:
3341 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003342 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003343 return 0;
3344 }
3345}
3346
Reid Spencere4d87aa2006-12-23 06:05:41 +00003347/// getICmpValue - This is the complement of getICmpCode, which turns an
3348/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003349/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003350/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003351static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003352 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003353 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003354 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003355 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003356 case 1:
3357 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003358 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003359 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003360 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3361 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003362 case 3:
3363 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003364 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003365 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003366 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003367 case 4:
3368 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003369 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003370 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003371 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3372 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003373 case 6:
3374 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003375 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003376 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003377 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003378 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003379 }
3380}
3381
Evan Cheng8db90722008-10-14 17:15:11 +00003382/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3383/// opcode and two operands into either a FCmp instruction. isordered is passed
3384/// in to determine which kind of predicate to use in the new fcmp instruction.
3385static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003386 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003387 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003388 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003389 case 0:
3390 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003391 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003392 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003393 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003394 case 1:
3395 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003396 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003397 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003398 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003399 case 2:
3400 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003401 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003402 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003403 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003404 case 3:
3405 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003406 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003407 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003408 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003409 case 4:
3410 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003411 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003412 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003413 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003414 case 5:
3415 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003416 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003417 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003418 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003419 case 6:
3420 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003421 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003422 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003423 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003424 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003425 }
3426}
3427
Chris Lattnerb9553d62008-11-16 04:55:20 +00003428/// PredicatesFoldable - Return true if both predicates match sign or if at
3429/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003430static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3431 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003432 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3433 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003434}
3435
3436namespace {
3437// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3438struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003439 InstCombiner &IC;
3440 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003441 ICmpInst::Predicate pred;
3442 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3443 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3444 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003445 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003446 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3447 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003448 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3449 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003450 return false;
3451 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003452 Instruction *apply(Instruction &Log) const {
3453 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3454 if (ICI->getOperand(0) != LHS) {
3455 assert(ICI->getOperand(1) == LHS);
3456 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003457 }
3458
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003459 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003460 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003461 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003462 unsigned Code;
3463 switch (Log.getOpcode()) {
3464 case Instruction::And: Code = LHSCode & RHSCode; break;
3465 case Instruction::Or: Code = LHSCode | RHSCode; break;
3466 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003467 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003468 }
3469
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003470 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3471 ICmpInst::isSignedPredicate(ICI->getPredicate());
3472
Owen Andersond672ecb2009-07-03 00:17:18 +00003473 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003474 if (Instruction *I = dyn_cast<Instruction>(RV))
3475 return I;
3476 // Otherwise, it's a constant boolean value...
3477 return IC.ReplaceInstUsesWith(Log, RV);
3478 }
3479};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003480} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003481
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003482// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3483// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003484// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003485Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003486 ConstantInt *OpRHS,
3487 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003488 BinaryOperator &TheAnd) {
3489 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003490 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003491 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003492 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003493
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003494 switch (Op->getOpcode()) {
3495 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003496 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003497 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003498 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003499 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003500 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003501 }
3502 break;
3503 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003504 if (Together == AndRHS) // (X | C) & C --> C
3505 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003506
Chris Lattner6e7ba452005-01-01 16:22:27 +00003507 if (Op->hasOneUse() && Together != OpRHS) {
3508 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003509 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003510 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003511 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003512 }
3513 break;
3514 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003515 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003516 // Adding a one to a single bit bit-field should be turned into an XOR
3517 // of the bit. First thing to check is to see if this AND is with a
3518 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003519 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003520
3521 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003522 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003523 // Ok, at this point, we know that we are masking the result of the
3524 // ADD down to exactly one bit. If the constant we are adding has
3525 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003526 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003527
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528 // Check to see if any bits below the one bit set in AndRHSV are set.
3529 if ((AddRHS & (AndRHSV-1)) == 0) {
3530 // If not, the only thing that can effect the output of the AND is
3531 // the bit specified by AndRHSV. If that bit is set, the effect of
3532 // the XOR is to toggle the bit. If it is clear, then the ADD has
3533 // no effect.
3534 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3535 TheAnd.setOperand(0, X);
3536 return &TheAnd;
3537 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003538 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003539 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003540 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003541 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003542 }
3543 }
3544 }
3545 }
3546 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003547
3548 case Instruction::Shl: {
3549 // We know that the AND will not produce any of the bits shifted in, so if
3550 // the anded constant includes them, clear them now!
3551 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003552 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003553 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003554 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003555 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003556
Zhou Sheng290bec52007-03-29 08:15:12 +00003557 if (CI->getValue() == ShlMask) {
3558 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003559 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3560 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003561 TheAnd.setOperand(1, CI);
3562 return &TheAnd;
3563 }
3564 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003565 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003566 case Instruction::LShr:
3567 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003568 // We know that the AND will not produce any of the bits shifted in, so if
3569 // the anded constant includes them, clear them now! This only applies to
3570 // unsigned shifts, because a signed shr may bring in set bits!
3571 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003572 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003573 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003574 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003575 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003576
Zhou Sheng290bec52007-03-29 08:15:12 +00003577 if (CI->getValue() == ShrMask) {
3578 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003579 return ReplaceInstUsesWith(TheAnd, Op);
3580 } else if (CI != AndRHS) {
3581 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3582 return &TheAnd;
3583 }
3584 break;
3585 }
3586 case Instruction::AShr:
3587 // Signed shr.
3588 // See if this is shifting in some sign extension, then masking it out
3589 // with an and.
3590 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003591 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003592 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003593 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003594 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003595 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003596 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003597 // Make the argument unsigned.
3598 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003599 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003600 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003601 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003602 }
3603 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003604 }
3605 return 0;
3606}
3607
Chris Lattner8b170942002-08-09 23:47:40 +00003608
Chris Lattnera96879a2004-09-29 17:40:11 +00003609/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3610/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003611/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3612/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003613/// insert new instructions.
3614Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003615 bool isSigned, bool Inside,
3616 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003617 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003618 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003619 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003620
Chris Lattnera96879a2004-09-29 17:40:11 +00003621 if (Inside) {
3622 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003623 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003624
Reid Spencere4d87aa2006-12-23 06:05:41 +00003625 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003626 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003627 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003628 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003629 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003630 }
3631
3632 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003633 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003634 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003635 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003636 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003637 }
3638
3639 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003640 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003641
Reid Spencere4e40032007-03-21 23:19:50 +00003642 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003643 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003644 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003645 ICmpInst::Predicate pred = (isSigned ?
3646 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003647 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003648 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003649
Reid Spencere4e40032007-03-21 23:19:50 +00003650 // Emit V-Lo >u Hi-1-Lo
3651 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003652 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003653 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003654 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003655 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003656}
3657
Chris Lattner7203e152005-09-18 07:22:02 +00003658// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3659// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3660// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3661// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003662static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003663 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003664 uint32_t BitWidth = Val->getType()->getBitWidth();
3665 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003666
3667 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003668 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003669 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003670 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003671 return true;
3672}
3673
Chris Lattner7203e152005-09-18 07:22:02 +00003674/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3675/// where isSub determines whether the operator is a sub. If we can fold one of
3676/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003677///
3678/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3679/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3680/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3681///
3682/// return (A +/- B).
3683///
3684Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003685 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003686 Instruction &I) {
3687 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3688 if (!LHSI || LHSI->getNumOperands() != 2 ||
3689 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3690
3691 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3692
3693 switch (LHSI->getOpcode()) {
3694 default: return 0;
3695 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003696 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003697 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003698 if ((Mask->getValue().countLeadingZeros() +
3699 Mask->getValue().countPopulation()) ==
3700 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003701 break;
3702
3703 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3704 // part, we don't need any explicit masks to take them out of A. If that
3705 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003706 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003707 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003708 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003709 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003710 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003711 break;
3712 }
3713 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003714 return 0;
3715 case Instruction::Or:
3716 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003717 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003718 if ((Mask->getValue().countLeadingZeros() +
3719 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003720 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003721 break;
3722 return 0;
3723 }
3724
Chris Lattnerc8e77562005-09-18 04:24:45 +00003725 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003726 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3727 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003728}
3729
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003730/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3731Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3732 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003733 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003734 ConstantInt *LHSCst, *RHSCst;
3735 ICmpInst::Predicate LHSCC, RHSCC;
3736
Chris Lattnerea065fb2008-11-16 05:10:52 +00003737 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003738 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003739 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003740 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003741 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003742 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003743
3744 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3745 // where C is a power of 2
3746 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3747 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003748 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003749 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003750 }
3751
3752 // From here on, we only handle:
3753 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3754 if (Val != Val2) return 0;
3755
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003756 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3757 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3758 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3759 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3760 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3761 return 0;
3762
3763 // We can't fold (ugt x, C) & (sgt x, C2).
3764 if (!PredicatesFoldable(LHSCC, RHSCC))
3765 return 0;
3766
3767 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003768 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003769 if (ICmpInst::isSignedPredicate(LHSCC) ||
3770 (ICmpInst::isEquality(LHSCC) &&
3771 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003772 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003773 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003774 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3775
3776 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003777 std::swap(LHS, RHS);
3778 std::swap(LHSCst, RHSCst);
3779 std::swap(LHSCC, RHSCC);
3780 }
3781
3782 // At this point, we know we have have two icmp instructions
3783 // comparing a value against two constants and and'ing the result
3784 // together. Because of the above check, we know that we only have
3785 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3786 // (from the FoldICmpLogical check above), that the two constants
3787 // are not equal and that the larger constant is on the RHS
3788 assert(LHSCst != RHSCst && "Compares not folded above?");
3789
3790 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003791 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003792 case ICmpInst::ICMP_EQ:
3793 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003794 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003795 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3796 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3797 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003798 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003799 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3800 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3801 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3802 return ReplaceInstUsesWith(I, LHS);
3803 }
3804 case ICmpInst::ICMP_NE:
3805 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003806 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003807 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003808 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003809 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003810 break; // (X != 13 & X u< 15) -> no change
3811 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003812 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003813 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003814 break; // (X != 13 & X s< 15) -> no change
3815 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3816 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3817 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3818 return ReplaceInstUsesWith(I, RHS);
3819 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003820 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003821 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003822 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003823 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003824 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003825 }
3826 break; // (X != 13 & X != 15) -> no change
3827 }
3828 break;
3829 case ICmpInst::ICMP_ULT:
3830 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003831 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003832 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3833 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003834 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003835 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3836 break;
3837 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3838 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3839 return ReplaceInstUsesWith(I, LHS);
3840 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3841 break;
3842 }
3843 break;
3844 case ICmpInst::ICMP_SLT:
3845 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003846 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003847 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3848 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003849 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003850 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3851 break;
3852 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3853 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3854 return ReplaceInstUsesWith(I, LHS);
3855 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3856 break;
3857 }
3858 break;
3859 case ICmpInst::ICMP_UGT:
3860 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003861 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3863 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3864 return ReplaceInstUsesWith(I, RHS);
3865 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3866 break;
3867 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003868 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003869 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003870 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003871 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003872 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003873 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3875 break;
3876 }
3877 break;
3878 case ICmpInst::ICMP_SGT:
3879 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003880 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003881 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3882 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3883 return ReplaceInstUsesWith(I, RHS);
3884 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3885 break;
3886 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003887 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003888 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003890 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003891 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003892 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003893 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3894 break;
3895 }
3896 break;
3897 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003898
3899 return 0;
3900}
3901
Chris Lattner42d1be02009-07-23 05:14:02 +00003902Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3903 FCmpInst *RHS) {
3904
3905 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3906 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3907 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3908 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3909 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3910 // If either of the constants are nans, then the whole thing returns
3911 // false.
3912 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003913 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003914 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003915 LHS->getOperand(0), RHS->getOperand(0));
3916 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003917
3918 // Handle vector zeros. This occurs because the canonical form of
3919 // "fcmp ord x,x" is "fcmp ord x, 0".
3920 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3921 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003922 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003923 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003924 return 0;
3925 }
3926
3927 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3928 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3929 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3930
3931
3932 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3933 // Swap RHS operands to match LHS.
3934 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3935 std::swap(Op1LHS, Op1RHS);
3936 }
3937
3938 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3939 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3940 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003941 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003942
3943 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003944 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003945 if (Op0CC == FCmpInst::FCMP_TRUE)
3946 return ReplaceInstUsesWith(I, RHS);
3947 if (Op1CC == FCmpInst::FCMP_TRUE)
3948 return ReplaceInstUsesWith(I, LHS);
3949
3950 bool Op0Ordered;
3951 bool Op1Ordered;
3952 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3953 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3954 if (Op1Pred == 0) {
3955 std::swap(LHS, RHS);
3956 std::swap(Op0Pred, Op1Pred);
3957 std::swap(Op0Ordered, Op1Ordered);
3958 }
3959 if (Op0Pred == 0) {
3960 // uno && ueq -> uno && (uno || eq) -> ueq
3961 // ord && olt -> ord && (ord && lt) -> olt
3962 if (Op0Ordered == Op1Ordered)
3963 return ReplaceInstUsesWith(I, RHS);
3964
3965 // uno && oeq -> uno && (ord && eq) -> false
3966 // uno && ord -> false
3967 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003968 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003969 // ord && ueq -> ord && (uno || eq) -> oeq
3970 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3971 Op0LHS, Op0RHS, Context));
3972 }
3973 }
3974
3975 return 0;
3976}
3977
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003978
Chris Lattner7e708292002-06-25 16:13:24 +00003979Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003980 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003981 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003982
Chris Lattnere87597f2004-10-16 18:11:37 +00003983 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003984 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003985
Chris Lattner6e7ba452005-01-01 16:22:27 +00003986 // and X, X = X
3987 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003988 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003989
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003990 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003991 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00003992 if (SimplifyDemandedInstructionBits(I))
3993 return &I;
3994 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003995 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003996 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003997 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003998 } else if (isa<ConstantAggregateZero>(Op1)) {
3999 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004000 }
4001 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004002
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004003 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004004 const APInt& AndRHSMask = AndRHS->getValue();
4005 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004006
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004007 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004008 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004009 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004010 Value *Op0LHS = Op0I->getOperand(0);
4011 Value *Op0RHS = Op0I->getOperand(1);
4012 switch (Op0I->getOpcode()) {
4013 case Instruction::Xor:
4014 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004015 // If the mask is only needed on one incoming arm, push it up.
4016 if (Op0I->hasOneUse()) {
4017 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4018 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004019 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4020 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004021 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004022 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004023 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004024 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004025 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4026 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004027 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4028 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004029 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004030 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4031 }
4032 }
4033
Chris Lattner6e7ba452005-01-01 16:22:27 +00004034 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004035 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004036 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4037 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4038 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4039 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004040 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004041 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004042 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004043 break;
4044
4045 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004046 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4047 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4048 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4049 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004050 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004051
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004052 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4053 // has 1's for all bits that the subtraction with A might affect.
4054 if (Op0I->hasOneUse()) {
4055 uint32_t BitWidth = AndRHSMask.getBitWidth();
4056 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4057 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4058
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004059 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004060 if (!(A && A->isZero()) && // avoid infinite recursion.
4061 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004062 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004063 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4064 }
4065 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004066 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004067
4068 case Instruction::Shl:
4069 case Instruction::LShr:
4070 // (1 << x) & 1 --> zext(x == 0)
4071 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004072 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004073 Value *NewICmp =
4074 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004075 return new ZExtInst(NewICmp, I.getType());
4076 }
4077 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004078 }
4079
Chris Lattner58403262003-07-23 19:25:52 +00004080 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004081 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004082 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004083 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004084 // If this is an integer truncation or change from signed-to-unsigned, and
4085 // if the source is an and/or with immediate, transform it. This
4086 // frequently occurs for bitfield accesses.
4087 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004088 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004089 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004090 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004091 if (CastOp->getOpcode() == Instruction::And) {
4092 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004093 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4094 // This will fold the two constants together, which may allow
4095 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004096 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004097 CastOp->getOperand(0), I.getType(),
4098 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004099 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004100 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004101 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004102 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004103 } else if (CastOp->getOpcode() == Instruction::Or) {
4104 // Change: and (cast (or X, C1) to T), C2
4105 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004106 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004107 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004108 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004109 return ReplaceInstUsesWith(I, AndRHS);
4110 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004111 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004112 }
Chris Lattner06782f82003-07-23 19:36:21 +00004113 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004114
4115 // Try to fold constant and into select arguments.
4116 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004117 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004118 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004119 if (isa<PHINode>(Op0))
4120 if (Instruction *NV = FoldOpIntoPhi(I))
4121 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004122 }
4123
Dan Gohman186a6362009-08-12 16:04:34 +00004124 Value *Op0NotVal = dyn_castNotVal(Op0);
4125 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004126
Chris Lattner5b62aa72004-06-18 06:07:51 +00004127 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004128 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004129
Misha Brukmancb6267b2004-07-30 12:50:08 +00004130 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004131 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004132 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4133 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004134 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004135 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004136
4137 {
Chris Lattner003b6202007-06-15 05:58:24 +00004138 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004139 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004140 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4141 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004142
4143 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004144 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004145 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004147 }
4148 }
4149
Dan Gohman4ae51262009-08-12 16:23:25 +00004150 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004151 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4152 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004153
4154 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004155 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004156 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004157 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004158 }
4159 }
Chris Lattner64daab52006-04-01 08:03:55 +00004160
4161 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004162 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004163 if (A == Op1) { // (A^B)&A -> A&(A^B)
4164 I.swapOperands(); // Simplify below
4165 std::swap(Op0, Op1);
4166 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4167 cast<BinaryOperator>(Op0)->swapOperands();
4168 I.swapOperands(); // Simplify below
4169 std::swap(Op0, Op1);
4170 }
4171 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004172
Chris Lattner64daab52006-04-01 08:03:55 +00004173 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004174 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004175 if (B == Op0) { // B&(A^B) -> B&(B^A)
4176 cast<BinaryOperator>(Op1)->swapOperands();
4177 std::swap(A, B);
4178 }
Chris Lattner74381062009-08-30 07:44:24 +00004179 if (A == Op0) // A&(A^B) -> A & ~B
4180 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004181 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004182
4183 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004184 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4185 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004186 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004187 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4188 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004189 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004190 }
4191
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4193 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004194 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004195 return R;
4196
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004197 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4198 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4199 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004200 }
4201
Chris Lattner6fc205f2006-05-05 06:39:07 +00004202 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004203 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4204 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4205 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4206 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004207 if (SrcTy == Op1C->getOperand(0)->getType() &&
4208 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004209 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004210 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4211 I.getType(), TD) &&
4212 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4213 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004214 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4215 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004216 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004217 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004218 }
Chris Lattnere511b742006-11-14 07:46:50 +00004219
4220 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004221 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4222 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4223 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004224 SI0->getOperand(1) == SI1->getOperand(1) &&
4225 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004226 Value *NewOp =
4227 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4228 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004229 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004230 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004231 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004232 }
4233
Evan Cheng8db90722008-10-14 17:15:11 +00004234 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004235 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004236 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4237 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4238 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004239 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004240
Chris Lattner7e708292002-06-25 16:13:24 +00004241 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004242}
4243
Chris Lattner8c34cd22008-10-05 02:13:19 +00004244/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4245/// capable of providing pieces of a bswap. The subexpression provides pieces
4246/// of a bswap if it is proven that each of the non-zero bytes in the output of
4247/// the expression came from the corresponding "byte swapped" byte in some other
4248/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4249/// we know that the expression deposits the low byte of %X into the high byte
4250/// of the bswap result and that all other bytes are zero. This expression is
4251/// accepted, the high byte of ByteValues is set to X to indicate a correct
4252/// match.
4253///
4254/// This function returns true if the match was unsuccessful and false if so.
4255/// On entry to the function the "OverallLeftShift" is a signed integer value
4256/// indicating the number of bytes that the subexpression is later shifted. For
4257/// example, if the expression is later right shifted by 16 bits, the
4258/// OverallLeftShift value would be -2 on entry. This is used to specify which
4259/// byte of ByteValues is actually being set.
4260///
4261/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4262/// byte is masked to zero by a user. For example, in (X & 255), X will be
4263/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4264/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4265/// always in the local (OverallLeftShift) coordinate space.
4266///
4267static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4268 SmallVector<Value*, 8> &ByteValues) {
4269 if (Instruction *I = dyn_cast<Instruction>(V)) {
4270 // If this is an or instruction, it may be an inner node of the bswap.
4271 if (I->getOpcode() == Instruction::Or) {
4272 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4273 ByteValues) ||
4274 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4275 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004276 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004277
4278 // If this is a logical shift by a constant multiple of 8, recurse with
4279 // OverallLeftShift and ByteMask adjusted.
4280 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4281 unsigned ShAmt =
4282 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4283 // Ensure the shift amount is defined and of a byte value.
4284 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4285 return true;
4286
4287 unsigned ByteShift = ShAmt >> 3;
4288 if (I->getOpcode() == Instruction::Shl) {
4289 // X << 2 -> collect(X, +2)
4290 OverallLeftShift += ByteShift;
4291 ByteMask >>= ByteShift;
4292 } else {
4293 // X >>u 2 -> collect(X, -2)
4294 OverallLeftShift -= ByteShift;
4295 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004296 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004297 }
4298
4299 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4300 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4301
4302 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4303 ByteValues);
4304 }
4305
4306 // If this is a logical 'and' with a mask that clears bytes, clear the
4307 // corresponding bytes in ByteMask.
4308 if (I->getOpcode() == Instruction::And &&
4309 isa<ConstantInt>(I->getOperand(1))) {
4310 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4311 unsigned NumBytes = ByteValues.size();
4312 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4313 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4314
4315 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4316 // If this byte is masked out by a later operation, we don't care what
4317 // the and mask is.
4318 if ((ByteMask & (1 << i)) == 0)
4319 continue;
4320
4321 // If the AndMask is all zeros for this byte, clear the bit.
4322 APInt MaskB = AndMask & Byte;
4323 if (MaskB == 0) {
4324 ByteMask &= ~(1U << i);
4325 continue;
4326 }
4327
4328 // If the AndMask is not all ones for this byte, it's not a bytezap.
4329 if (MaskB != Byte)
4330 return true;
4331
4332 // Otherwise, this byte is kept.
4333 }
4334
4335 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4336 ByteValues);
4337 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004338 }
4339
Chris Lattner8c34cd22008-10-05 02:13:19 +00004340 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4341 // the input value to the bswap. Some observations: 1) if more than one byte
4342 // is demanded from this input, then it could not be successfully assembled
4343 // into a byteswap. At least one of the two bytes would not be aligned with
4344 // their ultimate destination.
4345 if (!isPowerOf2_32(ByteMask)) return true;
4346 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004347
Chris Lattner8c34cd22008-10-05 02:13:19 +00004348 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4349 // is demanded, it needs to go into byte 0 of the result. This means that the
4350 // byte needs to be shifted until it lands in the right byte bucket. The
4351 // shift amount depends on the position: if the byte is coming from the high
4352 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4353 // low part, it must be shifted left.
4354 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4355 if (InputByteNo < ByteValues.size()/2) {
4356 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4357 return true;
4358 } else {
4359 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4360 return true;
4361 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004362
4363 // If the destination byte value is already defined, the values are or'd
4364 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004365 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004366 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004367 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004368 return false;
4369}
4370
4371/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4372/// If so, insert the new bswap intrinsic and return it.
4373Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004374 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004375 if (!ITy || ITy->getBitWidth() % 16 ||
4376 // ByteMask only allows up to 32-byte values.
4377 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004378 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004379
4380 /// ByteValues - For each byte of the result, we keep track of which value
4381 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004382 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004383 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004384
4385 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004386 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4387 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004388 return 0;
4389
4390 // Check to see if all of the bytes come from the same value.
4391 Value *V = ByteValues[0];
4392 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4393
4394 // Check to make sure that all of the bytes come from the same value.
4395 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4396 if (ByteValues[i] != V)
4397 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004398 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004399 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004400 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004401 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004402}
4403
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004404/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4405/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4406/// we can simplify this expression to "cond ? C : D or B".
4407static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004408 Value *C, Value *D,
4409 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004410 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004411 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004412 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004413 return 0;
4414
Chris Lattnera6a474d2008-11-16 04:26:55 +00004415 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004416 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004417 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004418 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004419 return SelectInst::Create(Cond, C, B);
4420 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004421 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004422 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004423 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004424 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004425 return 0;
4426}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004427
Chris Lattner69d4ced2008-11-16 05:20:07 +00004428/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4429Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4430 ICmpInst *LHS, ICmpInst *RHS) {
4431 Value *Val, *Val2;
4432 ConstantInt *LHSCst, *RHSCst;
4433 ICmpInst::Predicate LHSCC, RHSCC;
4434
4435 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004436 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004437 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004438 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004439 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004440 return 0;
4441
4442 // From here on, we only handle:
4443 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4444 if (Val != Val2) return 0;
4445
4446 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4447 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4448 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4449 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4450 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4451 return 0;
4452
4453 // We can't fold (ugt x, C) | (sgt x, C2).
4454 if (!PredicatesFoldable(LHSCC, RHSCC))
4455 return 0;
4456
4457 // Ensure that the larger constant is on the RHS.
4458 bool ShouldSwap;
4459 if (ICmpInst::isSignedPredicate(LHSCC) ||
4460 (ICmpInst::isEquality(LHSCC) &&
4461 ICmpInst::isSignedPredicate(RHSCC)))
4462 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4463 else
4464 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4465
4466 if (ShouldSwap) {
4467 std::swap(LHS, RHS);
4468 std::swap(LHSCst, RHSCst);
4469 std::swap(LHSCC, RHSCC);
4470 }
4471
4472 // At this point, we know we have have two icmp instructions
4473 // comparing a value against two constants and or'ing the result
4474 // together. Because of the above check, we know that we only have
4475 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4476 // FoldICmpLogical check above), that the two constants are not
4477 // equal.
4478 assert(LHSCst != RHSCst && "Compares not folded above?");
4479
4480 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004481 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004482 case ICmpInst::ICMP_EQ:
4483 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004484 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004485 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004486 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004487 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004488 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004489 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004490 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004491 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004492 }
4493 break; // (X == 13 | X == 15) -> no change
4494 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4495 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4496 break;
4497 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4498 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4499 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4500 return ReplaceInstUsesWith(I, RHS);
4501 }
4502 break;
4503 case ICmpInst::ICMP_NE:
4504 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004505 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004506 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4507 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4508 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4509 return ReplaceInstUsesWith(I, LHS);
4510 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4511 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4512 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004513 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004514 }
4515 break;
4516 case ICmpInst::ICMP_ULT:
4517 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004518 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004519 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4520 break;
4521 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4522 // If RHSCst is [us]MAXINT, it is always false. Not handling
4523 // this can cause overflow.
4524 if (RHSCst->isMaxValue(false))
4525 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004526 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004527 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004528 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4529 break;
4530 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4531 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4532 return ReplaceInstUsesWith(I, RHS);
4533 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4534 break;
4535 }
4536 break;
4537 case ICmpInst::ICMP_SLT:
4538 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004539 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004540 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4541 break;
4542 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4543 // If RHSCst is [us]MAXINT, it is always false. Not handling
4544 // this can cause overflow.
4545 if (RHSCst->isMaxValue(true))
4546 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004547 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004548 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004549 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4550 break;
4551 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4552 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4553 return ReplaceInstUsesWith(I, RHS);
4554 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4555 break;
4556 }
4557 break;
4558 case ICmpInst::ICMP_UGT:
4559 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004560 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004561 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4562 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4563 return ReplaceInstUsesWith(I, LHS);
4564 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4565 break;
4566 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4567 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004568 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004569 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4570 break;
4571 }
4572 break;
4573 case ICmpInst::ICMP_SGT:
4574 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004575 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004576 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4577 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4578 return ReplaceInstUsesWith(I, LHS);
4579 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4580 break;
4581 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4582 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004583 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4585 break;
4586 }
4587 break;
4588 }
4589 return 0;
4590}
4591
Chris Lattner5414cc52009-07-23 05:46:22 +00004592Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4593 FCmpInst *RHS) {
4594 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4595 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4596 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4597 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4598 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4599 // If either of the constants are nans, then the whole thing returns
4600 // true.
4601 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004602 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004603
4604 // Otherwise, no need to compare the two constants, compare the
4605 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004606 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004607 LHS->getOperand(0), RHS->getOperand(0));
4608 }
4609
4610 // Handle vector zeros. This occurs because the canonical form of
4611 // "fcmp uno x,x" is "fcmp uno x, 0".
4612 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4613 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004614 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004615 LHS->getOperand(0), RHS->getOperand(0));
4616
4617 return 0;
4618 }
4619
4620 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4621 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4622 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4623
4624 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4625 // Swap RHS operands to match LHS.
4626 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4627 std::swap(Op1LHS, Op1RHS);
4628 }
4629 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4630 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4631 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004632 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004633 Op0LHS, Op0RHS);
4634 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004635 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004636 if (Op0CC == FCmpInst::FCMP_FALSE)
4637 return ReplaceInstUsesWith(I, RHS);
4638 if (Op1CC == FCmpInst::FCMP_FALSE)
4639 return ReplaceInstUsesWith(I, LHS);
4640 bool Op0Ordered;
4641 bool Op1Ordered;
4642 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4643 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4644 if (Op0Ordered == Op1Ordered) {
4645 // If both are ordered or unordered, return a new fcmp with
4646 // or'ed predicates.
4647 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4648 Op0LHS, Op0RHS, Context);
4649 if (Instruction *I = dyn_cast<Instruction>(RV))
4650 return I;
4651 // Otherwise, it's a constant boolean value...
4652 return ReplaceInstUsesWith(I, RV);
4653 }
4654 }
4655 return 0;
4656}
4657
Bill Wendlinga698a472008-12-01 08:23:25 +00004658/// FoldOrWithConstants - This helper function folds:
4659///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004660/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004661///
4662/// into:
4663///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004664/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004665///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004666/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004667Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004668 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004669 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4670 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004671
Bill Wendling286a0542008-12-02 06:24:20 +00004672 Value *V1 = 0;
4673 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004674 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004675
Bill Wendling29976b92008-12-02 06:18:11 +00004676 APInt Xor = CI1->getValue() ^ CI2->getValue();
4677 if (!Xor.isAllOnesValue()) return 0;
4678
Bill Wendling286a0542008-12-02 06:24:20 +00004679 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004680 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004681 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004682 }
4683
4684 return 0;
4685}
4686
Chris Lattner7e708292002-06-25 16:13:24 +00004687Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004688 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004690
Chris Lattner42593e62007-03-24 23:56:43 +00004691 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004692 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004693
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004694 // or X, X = X
4695 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004696 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004697
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004698 // See if we can simplify any instructions used by the instruction whose sole
4699 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004700 if (SimplifyDemandedInstructionBits(I))
4701 return &I;
4702 if (isa<VectorType>(I.getType())) {
4703 if (isa<ConstantAggregateZero>(Op1)) {
4704 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4705 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4706 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4707 return ReplaceInstUsesWith(I, I.getOperand(1));
4708 }
Chris Lattner42593e62007-03-24 23:56:43 +00004709 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004710
Chris Lattner3f5b8772002-05-06 16:14:14 +00004711 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004712 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004713 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004714 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004715 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004716 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004717 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004718 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004719 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004720 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004721 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004722
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004723 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004724 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004725 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004726 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004727 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004728 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004729 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004730 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004731
4732 // Try to fold constant and into select arguments.
4733 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004734 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004735 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004736 if (isa<PHINode>(Op0))
4737 if (Instruction *NV = FoldOpIntoPhi(I))
4738 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004739 }
4740
Chris Lattner4f637d42006-01-06 17:59:59 +00004741 Value *A = 0, *B = 0;
4742 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004743
Dan Gohman4ae51262009-08-12 16:23:25 +00004744 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004745 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4746 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004747 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004748 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4749 return ReplaceInstUsesWith(I, Op0);
4750
Chris Lattner6423d4c2006-07-10 20:25:24 +00004751 // (A | B) | C and A | (B | C) -> bswap if possible.
4752 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004753 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4754 match(Op1, m_Or(m_Value(), m_Value())) ||
4755 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4756 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004757 if (Instruction *BSwap = MatchBSwap(I))
4758 return BSwap;
4759 }
4760
Chris Lattner6e4c6492005-05-09 04:58:36 +00004761 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004762 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004763 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004764 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004765 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004766 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004767 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004768 }
4769
4770 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004771 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004772 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004773 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004774 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004775 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004776 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004777 }
4778
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004779 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004780 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004781 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4782 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004783 Value *V1 = 0, *V2 = 0, *V3 = 0;
4784 C1 = dyn_cast<ConstantInt>(C);
4785 C2 = dyn_cast<ConstantInt>(D);
4786 if (C1 && C2) { // (A & C1)|(B & C2)
4787 // If we have: ((V + N) & C1) | (V & C2)
4788 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4789 // replace with V+N.
4790 if (C1->getValue() == ~C2->getValue()) {
4791 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004792 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004793 // Add commutes, try both ways.
4794 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4795 return ReplaceInstUsesWith(I, A);
4796 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4797 return ReplaceInstUsesWith(I, A);
4798 }
4799 // Or commutes, try both ways.
4800 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004801 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004802 // Add commutes, try both ways.
4803 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4804 return ReplaceInstUsesWith(I, B);
4805 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4806 return ReplaceInstUsesWith(I, B);
4807 }
4808 }
Chris Lattner044e5332007-04-08 08:01:49 +00004809 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004810 }
4811
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004812 // Check to see if we have any common things being and'ed. If so, find the
4813 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004814 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4815 if (A == B) // (A & C)|(A & D) == A & (C|D)
4816 V1 = A, V2 = C, V3 = D;
4817 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4818 V1 = A, V2 = B, V3 = C;
4819 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4820 V1 = C, V2 = A, V3 = D;
4821 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4822 V1 = C, V2 = A, V3 = B;
4823
4824 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004825 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004826 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004827 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004828 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004829
Dan Gohman1975d032008-10-30 20:40:10 +00004830 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004831 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004832 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004833 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004834 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004835 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004836 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004837 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004838 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004839
Bill Wendlingb01865c2008-11-30 13:52:49 +00004840 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004841 if ((match(C, m_Not(m_Specific(D))) &&
4842 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004843 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004844 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004845 if ((match(A, m_Not(m_Specific(D))) &&
4846 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004847 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004848 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004849 if ((match(C, m_Not(m_Specific(B))) &&
4850 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004852 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004853 if ((match(A, m_Not(m_Specific(B))) &&
4854 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004855 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004856 }
Chris Lattnere511b742006-11-14 07:46:50 +00004857
4858 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004859 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4860 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4861 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004862 SI0->getOperand(1) == SI1->getOperand(1) &&
4863 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004864 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4865 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004866 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004867 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004868 }
4869 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004870
Bill Wendlingb3833d12008-12-01 01:07:11 +00004871 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004872 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4873 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004874 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004875 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004876 }
4877 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004878 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4879 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004880 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004881 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004882 }
4883
Dan Gohman4ae51262009-08-12 16:23:25 +00004884 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004885 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004886 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004887 } else {
4888 A = 0;
4889 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004890 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004891 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004892 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004893 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004894
Misha Brukmancb6267b2004-07-30 12:50:08 +00004895 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004896 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004897 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004898 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004899 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004900 }
Chris Lattnera2881962003-02-18 19:28:33 +00004901
Reid Spencere4d87aa2006-12-23 06:05:41 +00004902 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4903 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004904 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004905 return R;
4906
Chris Lattner69d4ced2008-11-16 05:20:07 +00004907 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4908 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4909 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004910 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004911
4912 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004913 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004914 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004915 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004916 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4917 !isa<ICmpInst>(Op1C->getOperand(0))) {
4918 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004919 if (SrcTy == Op1C->getOperand(0)->getType() &&
4920 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004921 // Only do this if the casts both really cause code to be
4922 // generated.
4923 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4924 I.getType(), TD) &&
4925 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4926 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004927 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4928 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004929 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004930 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004931 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004932 }
Chris Lattner99c65742007-10-24 05:38:08 +00004933 }
4934
4935
4936 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4937 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004938 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4939 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4940 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004941 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004942
Chris Lattner7e708292002-06-25 16:13:24 +00004943 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004944}
4945
Dan Gohman844731a2008-05-13 00:00:25 +00004946namespace {
4947
Chris Lattnerc317d392004-02-16 01:20:27 +00004948// XorSelf - Implements: X ^ X --> 0
4949struct XorSelf {
4950 Value *RHS;
4951 XorSelf(Value *rhs) : RHS(rhs) {}
4952 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4953 Instruction *apply(BinaryOperator &Xor) const {
4954 return &Xor;
4955 }
4956};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004957
Dan Gohman844731a2008-05-13 00:00:25 +00004958}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004959
Chris Lattner7e708292002-06-25 16:13:24 +00004960Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004961 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004963
Evan Chengd34af782008-03-25 20:07:13 +00004964 if (isa<UndefValue>(Op1)) {
4965 if (isa<UndefValue>(Op0))
4966 // Handle undef ^ undef -> 0 special case. This is a common
4967 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004969 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004970 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004971
Chris Lattnerc317d392004-02-16 01:20:27 +00004972 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00004973 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004974 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00004975 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004976 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004977
4978 // See if we can simplify any instructions used by the instruction whose sole
4979 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004980 if (SimplifyDemandedInstructionBits(I))
4981 return &I;
4982 if (isa<VectorType>(I.getType()))
4983 if (isa<ConstantAggregateZero>(Op1))
4984 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00004985
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004986 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00004987 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004988 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4989 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4990 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4991 if (Op0I->getOpcode() == Instruction::And ||
4992 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00004993 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4994 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00004995 Value *NotY =
4996 Builder->CreateNot(Op0I->getOperand(1),
4997 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004998 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004999 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005000 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005001 }
5002 }
5003 }
5004 }
5005
5006
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005007 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005008 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005009 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005010 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005011 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005012 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005013
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005014 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005015 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005016 FCI->getOperand(0), FCI->getOperand(1));
5017 }
5018
Nick Lewycky517e1f52008-05-31 19:01:33 +00005019 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5020 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5021 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5022 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5023 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005024 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5025 (RHS == ConstantExpr::getCast(Opcode,
5026 ConstantInt::getTrue(*Context),
5027 Op0C->getDestTy()))) {
5028 CI->setPredicate(CI->getInversePredicate());
5029 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005030 }
5031 }
5032 }
5033 }
5034
Reid Spencere4d87aa2006-12-23 06:05:41 +00005035 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005036 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005037 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5038 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005039 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5040 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005041 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005042 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005043 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005044
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005045 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005046 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005047 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005048 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005049 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005050 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005051 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005052 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005053 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005054 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005055 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005056 Constant *C = ConstantInt::get(*Context,
5057 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005058 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005059
Chris Lattner7c4049c2004-01-12 19:35:11 +00005060 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005061 } else if (Op0I->getOpcode() == Instruction::Or) {
5062 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005063 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005064 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005065 // Anything in both C1 and C2 is known to be zero, remove it from
5066 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005067 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5068 NewRHS = ConstantExpr::getAnd(NewRHS,
5069 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005070 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005071 I.setOperand(0, Op0I->getOperand(0));
5072 I.setOperand(1, NewRHS);
5073 return &I;
5074 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005075 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005076 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005077 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005078
5079 // Try to fold constant and into select arguments.
5080 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005081 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005082 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005083 if (isa<PHINode>(Op0))
5084 if (Instruction *NV = FoldOpIntoPhi(I))
5085 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005086 }
5087
Dan Gohman186a6362009-08-12 16:04:34 +00005088 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005089 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005090 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005091
Dan Gohman186a6362009-08-12 16:04:34 +00005092 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005093 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005094 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005095
Chris Lattner318bf792007-03-18 22:51:34 +00005096
5097 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5098 if (Op1I) {
5099 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005100 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005101 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005102 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005103 I.swapOperands();
5104 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005105 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005106 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005107 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005108 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005109 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005110 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005111 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005112 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005113 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005114 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005115 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005116 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005117 std::swap(A, B);
5118 }
Chris Lattner318bf792007-03-18 22:51:34 +00005119 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005120 I.swapOperands(); // Simplified below.
5121 std::swap(Op0, Op1);
5122 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005123 }
Chris Lattner318bf792007-03-18 22:51:34 +00005124 }
5125
5126 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5127 if (Op0I) {
5128 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005129 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005130 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005131 if (A == Op1) // (B|A)^B == (A|B)^B
5132 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005133 if (B == Op1) // (A|B)^B == A & ~B
5134 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005135 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005136 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005137 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005138 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005139 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005140 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005141 if (A == Op1) // (A&B)^A -> (B&A)^A
5142 std::swap(A, B);
5143 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005144 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005145 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005146 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005147 }
Chris Lattner318bf792007-03-18 22:51:34 +00005148 }
5149
5150 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5151 if (Op0I && Op1I && Op0I->isShift() &&
5152 Op0I->getOpcode() == Op1I->getOpcode() &&
5153 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5154 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005155 Value *NewOp =
5156 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5157 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005158 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005159 Op1I->getOperand(1));
5160 }
5161
5162 if (Op0I && Op1I) {
5163 Value *A, *B, *C, *D;
5164 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005165 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5166 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005167 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005168 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005169 }
5170 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005171 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5172 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005173 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005174 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005175 }
5176
5177 // (A & B)^(C & D)
5178 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005179 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5180 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005181 // (X & Y)^(X & Y) -> (Y^Z) & X
5182 Value *X = 0, *Y = 0, *Z = 0;
5183 if (A == C)
5184 X = A, Y = B, Z = D;
5185 else if (A == D)
5186 X = A, Y = B, Z = C;
5187 else if (B == C)
5188 X = B, Y = A, Z = D;
5189 else if (B == D)
5190 X = B, Y = A, Z = C;
5191
5192 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005193 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005194 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005195 }
5196 }
5197 }
5198
Reid Spencere4d87aa2006-12-23 06:05:41 +00005199 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5200 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005201 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005202 return R;
5203
Chris Lattner6fc205f2006-05-05 06:39:07 +00005204 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005205 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005206 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005207 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5208 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005209 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005210 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005211 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5212 I.getType(), TD) &&
5213 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5214 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005215 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5216 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005217 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005218 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005219 }
Chris Lattner99c65742007-10-24 05:38:08 +00005220 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005221
Chris Lattner7e708292002-06-25 16:13:24 +00005222 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005223}
5224
Owen Andersond672ecb2009-07-03 00:17:18 +00005225static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005226 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005227 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005228}
Chris Lattnera96879a2004-09-29 17:40:11 +00005229
Dan Gohman6de29f82009-06-15 22:12:54 +00005230static bool HasAddOverflow(ConstantInt *Result,
5231 ConstantInt *In1, ConstantInt *In2,
5232 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005233 if (IsSigned)
5234 if (In2->getValue().isNegative())
5235 return Result->getValue().sgt(In1->getValue());
5236 else
5237 return Result->getValue().slt(In1->getValue());
5238 else
5239 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005240}
5241
Dan Gohman6de29f82009-06-15 22:12:54 +00005242/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005243/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005244static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005245 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005246 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005247 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005248
Dan Gohman6de29f82009-06-15 22:12:54 +00005249 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5250 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005251 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005252 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5253 ExtractElement(In1, Idx, Context),
5254 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005255 IsSigned))
5256 return true;
5257 }
5258 return false;
5259 }
5260
5261 return HasAddOverflow(cast<ConstantInt>(Result),
5262 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5263 IsSigned);
5264}
5265
5266static bool HasSubOverflow(ConstantInt *Result,
5267 ConstantInt *In1, ConstantInt *In2,
5268 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005269 if (IsSigned)
5270 if (In2->getValue().isNegative())
5271 return Result->getValue().slt(In1->getValue());
5272 else
5273 return Result->getValue().sgt(In1->getValue());
5274 else
5275 return Result->getValue().ugt(In1->getValue());
5276}
5277
Dan Gohman6de29f82009-06-15 22:12:54 +00005278/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5279/// overflowed for this type.
5280static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005281 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005282 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005283 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005284
5285 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5286 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005287 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005288 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5289 ExtractElement(In1, Idx, Context),
5290 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005291 IsSigned))
5292 return true;
5293 }
5294 return false;
5295 }
5296
5297 return HasSubOverflow(cast<ConstantInt>(Result),
5298 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5299 IsSigned);
5300}
5301
Chris Lattner574da9b2005-01-13 20:14:25 +00005302/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5303/// code necessary to compute the offset from the base pointer (without adding
5304/// in the base pointer). Return the result as a signed integer of intptr size.
5305static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005306 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005307 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005308 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005309 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005310
5311 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005312 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005313 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005314
Gabor Greif177dd3f2008-06-12 21:37:33 +00005315 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5316 ++i, ++GTI) {
5317 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005318 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005319 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5320 if (OpC->isZero()) continue;
5321
5322 // Handle a struct index, which adds its field offset to the pointer.
5323 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5324 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5325
Chris Lattner74381062009-08-30 07:44:24 +00005326 Result = IC.Builder->CreateAdd(Result,
5327 ConstantInt::get(IntPtrTy, Size),
5328 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005329 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005330 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005331
Owen Andersoneed707b2009-07-24 23:12:02 +00005332 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005333 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005334 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5335 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005336 // Emit an add instruction.
5337 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005338 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005339 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005340 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005341 if (Op->getType() != IntPtrTy)
5342 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005343 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005344 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005345 // We'll let instcombine(mul) convert this to a shl if possible.
5346 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005347 }
5348
5349 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005350 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005351 }
5352 return Result;
5353}
5354
Chris Lattner10c0d912008-04-22 02:53:33 +00005355
Dan Gohman8f080f02009-07-17 22:16:21 +00005356/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5357/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5358/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5359/// be complex, and scales are involved. The above expression would also be
5360/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5361/// This later form is less amenable to optimization though, and we are allowed
5362/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005363///
5364/// If we can't emit an optimized form for this expression, this returns null.
5365///
5366static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5367 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005368 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005369 gep_type_iterator GTI = gep_type_begin(GEP);
5370
5371 // Check to see if this gep only has a single variable index. If so, and if
5372 // any constant indices are a multiple of its scale, then we can compute this
5373 // in terms of the scale of the variable index. For example, if the GEP
5374 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5375 // because the expression will cross zero at the same point.
5376 unsigned i, e = GEP->getNumOperands();
5377 int64_t Offset = 0;
5378 for (i = 1; i != e; ++i, ++GTI) {
5379 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5380 // Compute the aggregate offset of constant indices.
5381 if (CI->isZero()) continue;
5382
5383 // Handle a struct index, which adds its field offset to the pointer.
5384 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5385 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5386 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005387 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005388 Offset += Size*CI->getSExtValue();
5389 }
5390 } else {
5391 // Found our variable index.
5392 break;
5393 }
5394 }
5395
5396 // If there are no variable indices, we must have a constant offset, just
5397 // evaluate it the general way.
5398 if (i == e) return 0;
5399
5400 Value *VariableIdx = GEP->getOperand(i);
5401 // Determine the scale factor of the variable element. For example, this is
5402 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005403 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005404
5405 // Verify that there are no other variable indices. If so, emit the hard way.
5406 for (++i, ++GTI; i != e; ++i, ++GTI) {
5407 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5408 if (!CI) return 0;
5409
5410 // Compute the aggregate offset of constant indices.
5411 if (CI->isZero()) continue;
5412
5413 // Handle a struct index, which adds its field offset to the pointer.
5414 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5415 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5416 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005417 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005418 Offset += Size*CI->getSExtValue();
5419 }
5420 }
5421
5422 // Okay, we know we have a single variable index, which must be a
5423 // pointer/array/vector index. If there is no offset, life is simple, return
5424 // the index.
5425 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5426 if (Offset == 0) {
5427 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5428 // we don't need to bother extending: the extension won't affect where the
5429 // computation crosses zero.
5430 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005431 VariableIdx = new TruncInst(VariableIdx,
5432 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005433 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005434 return VariableIdx;
5435 }
5436
5437 // Otherwise, there is an index. The computation we will do will be modulo
5438 // the pointer size, so get it.
5439 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5440
5441 Offset &= PtrSizeMask;
5442 VariableScale &= PtrSizeMask;
5443
5444 // To do this transformation, any constant index must be a multiple of the
5445 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5446 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5447 // multiple of the variable scale.
5448 int64_t NewOffs = Offset / (int64_t)VariableScale;
5449 if (Offset != NewOffs*(int64_t)VariableScale)
5450 return 0;
5451
5452 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005453 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005454 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005455 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005456 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005457 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005458 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005459 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005460}
5461
5462
Reid Spencere4d87aa2006-12-23 06:05:41 +00005463/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005464/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005465Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005466 ICmpInst::Predicate Cond,
5467 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005468 // Look through bitcasts.
5469 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5470 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005471
Chris Lattner574da9b2005-01-13 20:14:25 +00005472 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005473 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005474 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005475 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005476 // know pointers can't overflow since the gep is inbounds. See if we can
5477 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005478 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5479
5480 // If not, synthesize the offset the hard way.
5481 if (Offset == 0)
5482 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005483 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005484 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005485 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005486 // If the base pointers are different, but the indices are the same, just
5487 // compare the base pointer.
5488 if (PtrBase != GEPRHS->getOperand(0)) {
5489 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005490 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005491 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005492 if (IndicesTheSame)
5493 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5494 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5495 IndicesTheSame = false;
5496 break;
5497 }
5498
5499 // If all indices are the same, just compare the base pointers.
5500 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005501 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005502 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005503
5504 // Otherwise, the base pointers are different and the indices are
5505 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005506 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005507 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005508
Chris Lattnere9d782b2005-01-13 22:25:21 +00005509 // If one of the GEPs has all zero indices, recurse.
5510 bool AllZeros = true;
5511 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5512 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5513 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5514 AllZeros = false;
5515 break;
5516 }
5517 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005518 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5519 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005520
5521 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005522 AllZeros = true;
5523 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5524 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5525 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5526 AllZeros = false;
5527 break;
5528 }
5529 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005530 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005531
Chris Lattner4401c9c2005-01-14 00:20:05 +00005532 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5533 // If the GEPs only differ by one index, compare it.
5534 unsigned NumDifferences = 0; // Keep track of # differences.
5535 unsigned DiffOperand = 0; // The operand that differs.
5536 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5537 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005538 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5539 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005540 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005541 NumDifferences = 2;
5542 break;
5543 } else {
5544 if (NumDifferences++) break;
5545 DiffOperand = i;
5546 }
5547 }
5548
5549 if (NumDifferences == 0) // SAME GEP?
5550 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005551 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005552 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005553
Chris Lattner4401c9c2005-01-14 00:20:05 +00005554 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005555 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5556 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005557 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005558 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005559 }
5560 }
5561
Reid Spencere4d87aa2006-12-23 06:05:41 +00005562 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005563 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005564 if (TD &&
5565 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005566 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5567 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5568 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5569 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005570 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005571 }
5572 }
5573 return 0;
5574}
5575
Chris Lattnera5406232008-05-19 20:18:56 +00005576/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5577///
5578Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5579 Instruction *LHSI,
5580 Constant *RHSC) {
5581 if (!isa<ConstantFP>(RHSC)) return 0;
5582 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5583
5584 // Get the width of the mantissa. We don't want to hack on conversions that
5585 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005586 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005587 if (MantissaWidth == -1) return 0; // Unknown.
5588
5589 // Check to see that the input is converted from an integer type that is small
5590 // enough that preserves all bits. TODO: check here for "known" sign bits.
5591 // 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 +00005592 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005593
5594 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005595 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5596 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005597 ++InputSize;
5598
5599 // If the conversion would lose info, don't hack on this.
5600 if ((int)InputSize > MantissaWidth)
5601 return 0;
5602
5603 // Otherwise, we can potentially simplify the comparison. We know that it
5604 // will always come through as an integer value and we know the constant is
5605 // not a NAN (it would have been previously simplified).
5606 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5607
5608 ICmpInst::Predicate Pred;
5609 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005610 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005611 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005612 case FCmpInst::FCMP_OEQ:
5613 Pred = ICmpInst::ICMP_EQ;
5614 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005615 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005616 case FCmpInst::FCMP_OGT:
5617 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5618 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005619 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005620 case FCmpInst::FCMP_OGE:
5621 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5622 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005623 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005624 case FCmpInst::FCMP_OLT:
5625 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5626 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005627 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005628 case FCmpInst::FCMP_OLE:
5629 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5630 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005631 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005632 case FCmpInst::FCMP_ONE:
5633 Pred = ICmpInst::ICMP_NE;
5634 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005635 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005636 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005637 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005638 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005639 }
5640
5641 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5642
5643 // Now we know that the APFloat is a normal number, zero or inf.
5644
Chris Lattner85162782008-05-20 03:50:52 +00005645 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005646 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005647 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005648
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005649 if (!LHSUnsigned) {
5650 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5651 // and large values.
5652 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5653 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5654 APFloat::rmNearestTiesToEven);
5655 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5656 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5657 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005658 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5659 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005660 }
5661 } else {
5662 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5663 // +INF and large values.
5664 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5665 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5666 APFloat::rmNearestTiesToEven);
5667 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5668 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5669 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005670 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5671 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005672 }
Chris Lattnera5406232008-05-19 20:18:56 +00005673 }
5674
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005675 if (!LHSUnsigned) {
5676 // See if the RHS value is < SignedMin.
5677 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5678 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5679 APFloat::rmNearestTiesToEven);
5680 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5681 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5682 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005683 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5684 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005685 }
Chris Lattnera5406232008-05-19 20:18:56 +00005686 }
5687
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005688 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5689 // [0, UMAX], but it may still be fractional. See if it is fractional by
5690 // casting the FP value to the integer value and back, checking for equality.
5691 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005692 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005693 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5694 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005695 if (!RHS.isZero()) {
5696 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005697 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5698 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005699 if (!Equal) {
5700 // If we had a comparison against a fractional value, we have to adjust
5701 // the compare predicate and sometimes the value. RHSC is rounded towards
5702 // zero at this point.
5703 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005704 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005705 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005707 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005708 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005709 case ICmpInst::ICMP_ULE:
5710 // (float)int <= 4.4 --> int <= 4
5711 // (float)int <= -4.4 --> false
5712 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005713 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005714 break;
5715 case ICmpInst::ICMP_SLE:
5716 // (float)int <= 4.4 --> int <= 4
5717 // (float)int <= -4.4 --> int < -4
5718 if (RHS.isNegative())
5719 Pred = ICmpInst::ICMP_SLT;
5720 break;
5721 case ICmpInst::ICMP_ULT:
5722 // (float)int < -4.4 --> false
5723 // (float)int < 4.4 --> int <= 4
5724 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005725 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005726 Pred = ICmpInst::ICMP_ULE;
5727 break;
5728 case ICmpInst::ICMP_SLT:
5729 // (float)int < -4.4 --> int < -4
5730 // (float)int < 4.4 --> int <= 4
5731 if (!RHS.isNegative())
5732 Pred = ICmpInst::ICMP_SLE;
5733 break;
5734 case ICmpInst::ICMP_UGT:
5735 // (float)int > 4.4 --> int > 4
5736 // (float)int > -4.4 --> true
5737 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005738 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005739 break;
5740 case ICmpInst::ICMP_SGT:
5741 // (float)int > 4.4 --> int > 4
5742 // (float)int > -4.4 --> int >= -4
5743 if (RHS.isNegative())
5744 Pred = ICmpInst::ICMP_SGE;
5745 break;
5746 case ICmpInst::ICMP_UGE:
5747 // (float)int >= -4.4 --> true
5748 // (float)int >= 4.4 --> int > 4
5749 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005750 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005751 Pred = ICmpInst::ICMP_UGT;
5752 break;
5753 case ICmpInst::ICMP_SGE:
5754 // (float)int >= -4.4 --> int >= -4
5755 // (float)int >= 4.4 --> int > 4
5756 if (!RHS.isNegative())
5757 Pred = ICmpInst::ICMP_SGT;
5758 break;
5759 }
Chris Lattnera5406232008-05-19 20:18:56 +00005760 }
5761 }
5762
5763 // Lower this FP comparison into an appropriate integer version of the
5764 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005765 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005766}
5767
Reid Spencere4d87aa2006-12-23 06:05:41 +00005768Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5769 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005770 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005771
Chris Lattner58e97462007-01-14 19:42:17 +00005772 // Fold trivial predicates.
5773 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005774 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005775 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005777
5778 // Simplify 'fcmp pred X, X'
5779 if (Op0 == Op1) {
5780 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005781 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005782 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5783 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5784 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005785 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005786 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5787 case FCmpInst::FCMP_OLT: // True if ordered and less than
5788 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005790
5791 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5792 case FCmpInst::FCMP_ULT: // True if unordered or less than
5793 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5794 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5795 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5796 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005797 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005798 return &I;
5799
5800 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5801 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5802 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5803 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5804 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5805 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005806 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005807 return &I;
5808 }
5809 }
5810
Reid Spencere4d87aa2006-12-23 06:05:41 +00005811 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005812 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005813
Reid Spencere4d87aa2006-12-23 06:05:41 +00005814 // Handle fcmp with constant RHS
5815 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005816 // If the constant is a nan, see if we can fold the comparison based on it.
5817 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5818 if (CFP->getValueAPF().isNaN()) {
5819 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005820 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005821 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5822 "Comparison must be either ordered or unordered!");
5823 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005825 }
5826 }
5827
Reid Spencere4d87aa2006-12-23 06:05:41 +00005828 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5829 switch (LHSI->getOpcode()) {
5830 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005831 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5832 // block. If in the same block, we're encouraging jump threading. If
5833 // not, we are just pessimizing the code by making an i1 phi.
5834 if (LHSI->getParent() == I.getParent())
5835 if (Instruction *NV = FoldOpIntoPhi(I))
5836 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005837 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005838 case Instruction::SIToFP:
5839 case Instruction::UIToFP:
5840 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5841 return NV;
5842 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005843 case Instruction::Select:
5844 // If either operand of the select is a constant, we can fold the
5845 // comparison into the select arms, which will cause one to be
5846 // constant folded and the select turned into a bitwise or.
5847 Value *Op1 = 0, *Op2 = 0;
5848 if (LHSI->hasOneUse()) {
5849 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5850 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005851 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005852 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005853 Op2 = Builder->CreateFCmp(I.getPredicate(),
5854 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005855 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5856 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005857 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005858 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005859 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5860 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005861 }
5862 }
5863
5864 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005865 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005866 break;
5867 }
5868 }
5869
5870 return Changed ? &I : 0;
5871}
5872
5873Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5874 bool Changed = SimplifyCompare(I);
5875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5876 const Type *Ty = Op0->getType();
5877
5878 // icmp X, X
5879 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005880 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005881 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005882
5883 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005884 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005885
Reid Spencere4d87aa2006-12-23 06:05:41 +00005886 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005887 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005888 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5889 isa<ConstantPointerNull>(Op0)) &&
5890 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005891 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005892 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005893 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005894
Reid Spencere4d87aa2006-12-23 06:05:41 +00005895 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005896 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005897 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005898 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005899 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005900 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005901 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005902 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005903 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005904 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005905
Reid Spencere4d87aa2006-12-23 06:05:41 +00005906 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005907 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005908 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005909 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005910 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005911 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005912 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005913 case ICmpInst::ICMP_SGT:
5914 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005915 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005916 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005917 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005918 return BinaryOperator::CreateAnd(Not, Op0);
5919 }
5920 case ICmpInst::ICMP_UGE:
5921 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5922 // FALL THROUGH
5923 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005924 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005925 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005926 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005927 case ICmpInst::ICMP_SGE:
5928 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5929 // FALL THROUGH
5930 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005931 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005932 return BinaryOperator::CreateOr(Not, Op0);
5933 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005934 }
Chris Lattner8b170942002-08-09 23:47:40 +00005935 }
5936
Dan Gohman1c8491e2009-04-25 17:12:48 +00005937 unsigned BitWidth = 0;
5938 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005939 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5940 else if (Ty->isIntOrIntVector())
5941 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005942
5943 bool isSignBit = false;
5944
Dan Gohman81b28ce2008-09-16 18:46:06 +00005945 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005946 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005947 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005948
Chris Lattnerb6566012008-01-05 01:18:20 +00005949 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5950 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005951 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005952 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005953 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005954 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005955
Dan Gohman81b28ce2008-09-16 18:46:06 +00005956 // If we have an icmp le or icmp ge instruction, turn it into the
5957 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5958 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005959 switch (I.getPredicate()) {
5960 default: break;
5961 case ICmpInst::ICMP_ULE:
5962 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005963 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005964 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005965 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005966 case ICmpInst::ICMP_SLE:
5967 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005968 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005969 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005970 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005971 case ICmpInst::ICMP_UGE:
5972 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005973 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005974 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005975 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005976 case ICmpInst::ICMP_SGE:
5977 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005978 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005979 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005980 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005981 }
5982
Chris Lattner183661e2008-07-11 05:40:05 +00005983 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00005984 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00005985 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00005986 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5987 }
5988
5989 // See if we can fold the comparison based on range information we can get
5990 // by checking whether bits are known to be zero or one in the input.
5991 if (BitWidth != 0) {
5992 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5993 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5994
5995 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00005996 isSignBit ? APInt::getSignBit(BitWidth)
5997 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00005998 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005999 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006000 if (SimplifyDemandedBits(I.getOperandUse(1),
6001 APInt::getAllOnesValue(BitWidth),
6002 Op1KnownZero, Op1KnownOne, 0))
6003 return &I;
6004
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006005 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006006 // in. Compute the Min, Max and RHS values based on the known bits. For the
6007 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006008 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6009 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6010 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6011 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6012 Op0Min, Op0Max);
6013 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6014 Op1Min, Op1Max);
6015 } else {
6016 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6017 Op0Min, Op0Max);
6018 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6019 Op1Min, Op1Max);
6020 }
6021
Chris Lattner183661e2008-07-11 05:40:05 +00006022 // If Min and Max are known to be the same, then SimplifyDemandedBits
6023 // figured out that the LHS is a constant. Just constant fold this now so
6024 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006025 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006026 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006027 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006028 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006029 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006030 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006031
Chris Lattner183661e2008-07-11 05:40:05 +00006032 // Based on the range information we know about the LHS, see if we can
6033 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006034 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006035 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006036 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006037 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006038 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006039 break;
6040 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006041 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006042 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006043 break;
6044 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006045 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006046 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006047 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006048 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006049 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006050 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006051 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6052 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006053 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006054 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055
6056 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6057 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006058 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006059 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006060 }
Chris Lattner84dff672008-07-11 05:08:55 +00006061 break;
6062 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006063 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006064 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006065 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006066 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006067
6068 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006069 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006070 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006072 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006073 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074
6075 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6076 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006077 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006078 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006079 }
Chris Lattner84dff672008-07-11 05:08:55 +00006080 break;
6081 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006083 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006084 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006085 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006086 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006087 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006088 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6089 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006090 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006091 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006092 }
Chris Lattner84dff672008-07-11 05:08:55 +00006093 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094 case ICmpInst::ICMP_SGT:
6095 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006097 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006098 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006099
6100 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006101 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006102 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6103 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006104 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006105 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106 }
6107 break;
6108 case ICmpInst::ICMP_SGE:
6109 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6110 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006111 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006112 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006113 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006114 break;
6115 case ICmpInst::ICMP_SLE:
6116 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6117 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006118 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006120 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 break;
6122 case ICmpInst::ICMP_UGE:
6123 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6124 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006125 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006127 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006128 break;
6129 case ICmpInst::ICMP_ULE:
6130 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6131 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006132 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006134 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006135 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006136 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006137
6138 // Turn a signed comparison into an unsigned one if both operands
6139 // are known to have the same sign.
6140 if (I.isSignedPredicate() &&
6141 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6142 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006143 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006144 }
6145
6146 // Test if the ICmpInst instruction is used exclusively by a select as
6147 // part of a minimum or maximum operation. If so, refrain from doing
6148 // any other folding. This helps out other analyses which understand
6149 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6150 // and CodeGen. And in this case, at least one of the comparison
6151 // operands has at least one user besides the compare (the select),
6152 // which would often largely negate the benefit of folding anyway.
6153 if (I.hasOneUse())
6154 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6155 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6156 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6157 return 0;
6158
6159 // See if we are doing a comparison between a constant and an instruction that
6160 // can be folded into the comparison.
6161 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006162 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006163 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006164 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006165 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006166 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6167 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006168 }
6169
Chris Lattner01deb9d2007-04-03 17:43:25 +00006170 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006171 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6172 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6173 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006174 case Instruction::GetElementPtr:
6175 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006176 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006177 bool isAllZeros = true;
6178 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6179 if (!isa<Constant>(LHSI->getOperand(i)) ||
6180 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6181 isAllZeros = false;
6182 break;
6183 }
6184 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006185 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006186 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006187 }
6188 break;
6189
Chris Lattner6970b662005-04-23 15:31:55 +00006190 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006191 // Only fold icmp into the PHI if the phi and fcmp are in the same
6192 // block. If in the same block, we're encouraging jump threading. If
6193 // not, we are just pessimizing the code by making an i1 phi.
6194 if (LHSI->getParent() == I.getParent())
6195 if (Instruction *NV = FoldOpIntoPhi(I))
6196 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006197 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006198 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006199 // If either operand of the select is a constant, we can fold the
6200 // comparison into the select arms, which will cause one to be
6201 // constant folded and the select turned into a bitwise or.
6202 Value *Op1 = 0, *Op2 = 0;
6203 if (LHSI->hasOneUse()) {
6204 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6205 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006206 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006207 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006208 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6209 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006210 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6211 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006212 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006213 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006214 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6215 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006216 }
6217 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006218
Chris Lattner6970b662005-04-23 15:31:55 +00006219 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006220 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006221 break;
6222 }
Chris Lattner4802d902007-04-06 18:57:34 +00006223 case Instruction::Malloc:
6224 // If we have (malloc != null), and if the malloc has a single use, we
6225 // can assume it is successful and remove the malloc.
6226 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006227 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006228 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006229 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006230 }
6231 break;
6232 }
Chris Lattner6970b662005-04-23 15:31:55 +00006233 }
6234
Reid Spencere4d87aa2006-12-23 06:05:41 +00006235 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006236 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006237 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006238 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006239 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006240 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6241 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006242 return NI;
6243
Reid Spencere4d87aa2006-12-23 06:05:41 +00006244 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006245 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6246 // now.
6247 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6248 if (isa<PointerType>(Op0->getType()) &&
6249 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006250 // We keep moving the cast from the left operand over to the right
6251 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006252 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006253
Chris Lattner57d86372007-01-06 01:45:59 +00006254 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6255 // so eliminate it as well.
6256 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6257 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006258
Chris Lattnerde90b762003-11-03 04:25:02 +00006259 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006260 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006261 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006262 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006263 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006264 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006265 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006266 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006267 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006268 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006269 }
Chris Lattner57d86372007-01-06 01:45:59 +00006270 }
6271
6272 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006273 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006274 // This comes up when you have code like
6275 // int X = A < B;
6276 // if (X) ...
6277 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006278 // with a constant or another cast from the same type.
6279 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006280 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006281 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006282 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006283
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006284 // See if it's the same type of instruction on the left and right.
6285 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6286 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006287 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006288 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006289 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006290 default: break;
6291 case Instruction::Add:
6292 case Instruction::Sub:
6293 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006294 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006295 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006296 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006297 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6298 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6299 if (CI->getValue().isSignBit()) {
6300 ICmpInst::Predicate Pred = I.isSignedPredicate()
6301 ? I.getUnsignedPredicate()
6302 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006303 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006304 Op1I->getOperand(0));
6305 }
6306
6307 if (CI->getValue().isMaxSignedValue()) {
6308 ICmpInst::Predicate Pred = I.isSignedPredicate()
6309 ? I.getUnsignedPredicate()
6310 : I.getSignedPredicate();
6311 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006312 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006313 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006314 }
6315 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006316 break;
6317 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006318 if (!I.isEquality())
6319 break;
6320
Nick Lewycky5d52c452008-08-21 05:56:10 +00006321 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6322 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6323 // Mask = -1 >> count-trailing-zeros(Cst).
6324 if (!CI->isZero() && !CI->isOne()) {
6325 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006326 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006327 APInt::getLowBitsSet(AP.getBitWidth(),
6328 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006329 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006330 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6331 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006332 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006333 }
6334 }
6335 break;
6336 }
6337 }
6338 }
6339 }
6340
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006341 // ~x < ~y --> y < x
6342 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006343 if (match(Op0, m_Not(m_Value(A))) &&
6344 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006345 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006346 }
6347
Chris Lattner65b72ba2006-09-18 04:22:48 +00006348 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006349 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006350
6351 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006352 if (match(Op0, m_Neg(m_Value(A))) &&
6353 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006354 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006355
Dan Gohman4ae51262009-08-12 16:23:25 +00006356 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006357 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6358 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006359 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006360 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006361 }
6362
Dan Gohman4ae51262009-08-12 16:23:25 +00006363 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006364 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006365 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006366 if (match(B, m_ConstantInt(C1)) &&
6367 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006368 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006369 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006370 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6371 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006372 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006373
6374 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006375 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6376 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6377 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6378 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006379 }
6380 }
6381
Dan Gohman4ae51262009-08-12 16:23:25 +00006382 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006383 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006384 // A == (A^B) -> B == 0
6385 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006386 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006387 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006388 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006389
6390 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006391 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006392 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006393 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006394
6395 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006396 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006397 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006398 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006399
Chris Lattner9c2328e2006-11-14 06:06:06 +00006400 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6401 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006402 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6403 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006404 Value *X = 0, *Y = 0, *Z = 0;
6405
6406 if (A == C) {
6407 X = B; Y = D; Z = A;
6408 } else if (A == D) {
6409 X = B; Y = C; Z = A;
6410 } else if (B == C) {
6411 X = A; Y = D; Z = B;
6412 } else if (B == D) {
6413 X = A; Y = C; Z = B;
6414 }
6415
6416 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006417 Op1 = Builder->CreateXor(X, Y, "tmp");
6418 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006419 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006420 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006421 return &I;
6422 }
6423 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006424 }
Chris Lattner7e708292002-06-25 16:13:24 +00006425 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006426}
6427
Chris Lattner562ef782007-06-20 23:46:26 +00006428
6429/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6430/// and CmpRHS are both known to be integer constants.
6431Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6432 ConstantInt *DivRHS) {
6433 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6434 const APInt &CmpRHSV = CmpRHS->getValue();
6435
6436 // FIXME: If the operand types don't match the type of the divide
6437 // then don't attempt this transform. The code below doesn't have the
6438 // logic to deal with a signed divide and an unsigned compare (and
6439 // vice versa). This is because (x /s C1) <s C2 produces different
6440 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6441 // (x /u C1) <u C2. Simply casting the operands and result won't
6442 // work. :( The if statement below tests that condition and bails
6443 // if it finds it.
6444 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6445 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6446 return 0;
6447 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006448 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006449 if (DivIsSigned && DivRHS->isAllOnesValue())
6450 return 0; // The overflow computation also screws up here
6451 if (DivRHS->isOne())
6452 return 0; // Not worth bothering, and eliminates some funny cases
6453 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006454
6455 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6456 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6457 // C2 (CI). By solving for X we can turn this into a range check
6458 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006459 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006460
6461 // Determine if the product overflows by seeing if the product is
6462 // not equal to the divide. Make sure we do the same kind of divide
6463 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006464 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6465 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006466
6467 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006468 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006469
Chris Lattner1dbfd482007-06-21 18:11:19 +00006470 // Figure out the interval that is being checked. For example, a comparison
6471 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6472 // Compute this interval based on the constants involved and the signedness of
6473 // the compare/divide. This computes a half-open interval, keeping track of
6474 // whether either value in the interval overflows. After analysis each
6475 // overflow variable is set to 0 if it's corresponding bound variable is valid
6476 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6477 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006478 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006479
Chris Lattner562ef782007-06-20 23:46:26 +00006480 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006481 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006482 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006483 HiOverflow = LoOverflow = ProdOV;
6484 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006485 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006486 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006487 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006488 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006489 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006490 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006491 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006492 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6493 HiOverflow = LoOverflow = ProdOV;
6494 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006495 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006496 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006497 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006498 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006499 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6500 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006501 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006502 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006503 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006504 true) ? -1 : 0;
6505 }
Chris Lattner562ef782007-06-20 23:46:26 +00006506 }
Dan Gohman76491272008-02-13 22:09:18 +00006507 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006508 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006509 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006510 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006511 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006512 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6513 HiOverflow = 1; // [INTMIN+1, overflow)
6514 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6515 }
Dan Gohman76491272008-02-13 22:09:18 +00006516 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006517 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006518 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006519 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006520 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006521 LoOverflow = AddWithOverflow(LoBound, HiBound,
6522 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006523 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006524 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6525 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006526 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006527 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006528 }
6529
Chris Lattner1dbfd482007-06-21 18:11:19 +00006530 // Dividing by a negative swaps the condition. LT <-> GT
6531 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006532 }
6533
6534 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006535 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006536 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006537 case ICmpInst::ICMP_EQ:
6538 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006539 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006540 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006541 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006542 ICmpInst::ICMP_UGE, X, LoBound);
6543 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006544 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006545 ICmpInst::ICMP_ULT, X, HiBound);
6546 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006547 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006548 case ICmpInst::ICMP_NE:
6549 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006550 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006551 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006552 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006553 ICmpInst::ICMP_ULT, X, LoBound);
6554 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006555 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006556 ICmpInst::ICMP_UGE, X, HiBound);
6557 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006558 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006559 case ICmpInst::ICMP_ULT:
6560 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006561 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006562 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006563 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006564 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006565 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006566 case ICmpInst::ICMP_UGT:
6567 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006568 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006569 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006570 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006571 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006572 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006573 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006574 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006575 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006576 }
6577}
6578
6579
Chris Lattner01deb9d2007-04-03 17:43:25 +00006580/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6581///
6582Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6583 Instruction *LHSI,
6584 ConstantInt *RHS) {
6585 const APInt &RHSV = RHS->getValue();
6586
6587 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006588 case Instruction::Trunc:
6589 if (ICI.isEquality() && LHSI->hasOneUse()) {
6590 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6591 // of the high bits truncated out of x are known.
6592 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6593 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6594 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6595 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6596 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6597
6598 // If all the high bits are known, we can do this xform.
6599 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6600 // Pull in the high bits from known-ones set.
6601 APInt NewRHS(RHS->getValue());
6602 NewRHS.zext(SrcBits);
6603 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006604 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006605 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006606 }
6607 }
6608 break;
6609
Duncan Sands0091bf22007-04-04 06:42:45 +00006610 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006611 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6612 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6613 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006614 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6615 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006616 Value *CompareVal = LHSI->getOperand(0);
6617
6618 // If the sign bit of the XorCST is not set, there is no change to
6619 // the operation, just stop using the Xor.
6620 if (!XorCST->getValue().isNegative()) {
6621 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006622 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006623 return &ICI;
6624 }
6625
6626 // Was the old condition true if the operand is positive?
6627 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6628
6629 // If so, the new one isn't.
6630 isTrueIfPositive ^= true;
6631
6632 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006633 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006634 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006635 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006636 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006637 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006638 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006639
6640 if (LHSI->hasOneUse()) {
6641 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6642 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6643 const APInt &SignBit = XorCST->getValue();
6644 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6645 ? ICI.getUnsignedPredicate()
6646 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006647 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006648 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006649 }
6650
6651 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006652 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006653 const APInt &NotSignBit = XorCST->getValue();
6654 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6655 ? ICI.getUnsignedPredicate()
6656 : ICI.getSignedPredicate();
6657 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006658 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006659 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006660 }
6661 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006662 }
6663 break;
6664 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6665 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6666 LHSI->getOperand(0)->hasOneUse()) {
6667 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6668
6669 // If the LHS is an AND of a truncating cast, we can widen the
6670 // and/compare to be the input width without changing the value
6671 // produced, eliminating a cast.
6672 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6673 // We can do this transformation if either the AND constant does not
6674 // have its sign bit set or if it is an equality comparison.
6675 // Extending a relational comparison when we're checking the sign
6676 // bit would not work.
6677 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006678 (ICI.isEquality() ||
6679 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006680 uint32_t BitWidth =
6681 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6682 APInt NewCST = AndCST->getValue();
6683 NewCST.zext(BitWidth);
6684 APInt NewCI = RHSV;
6685 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006686 Value *NewAnd =
6687 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006688 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006689 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006690 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006691 }
6692 }
6693
6694 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6695 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6696 // happens a LOT in code produced by the C front-end, for bitfield
6697 // access.
6698 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6699 if (Shift && !Shift->isShift())
6700 Shift = 0;
6701
6702 ConstantInt *ShAmt;
6703 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6704 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6705 const Type *AndTy = AndCST->getType(); // Type of the and.
6706
6707 // We can fold this as long as we can't shift unknown bits
6708 // into the mask. This can only happen with signed shift
6709 // rights, as they sign-extend.
6710 if (ShAmt) {
6711 bool CanFold = Shift->isLogicalShift();
6712 if (!CanFold) {
6713 // To test for the bad case of the signed shr, see if any
6714 // of the bits shifted in could be tested after the mask.
6715 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6716 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6717
6718 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6719 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6720 AndCST->getValue()) == 0)
6721 CanFold = true;
6722 }
6723
6724 if (CanFold) {
6725 Constant *NewCst;
6726 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006727 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006728 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006729 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006730
6731 // Check to see if we are shifting out any of the bits being
6732 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006733 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006734 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006735 // If we shifted bits out, the fold is not going to work out.
6736 // As a special case, check to see if this means that the
6737 // result is always true or false now.
6738 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006739 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006740 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006741 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006742 } else {
6743 ICI.setOperand(1, NewCst);
6744 Constant *NewAndCST;
6745 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006746 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006747 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006748 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006749 LHSI->setOperand(1, NewAndCST);
6750 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006751 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006752 return &ICI;
6753 }
6754 }
6755 }
6756
6757 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6758 // preferable because it allows the C<<Y expression to be hoisted out
6759 // of a loop if Y is invariant and X is not.
6760 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006761 ICI.isEquality() && !Shift->isArithmeticShift() &&
6762 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006763 // Compute C << Y.
6764 Value *NS;
6765 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006766 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006767 } else {
6768 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006769 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006770 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006771
6772 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006773 Value *NewAnd =
6774 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006775
6776 ICI.setOperand(0, NewAnd);
6777 return &ICI;
6778 }
6779 }
6780 break;
6781
Chris Lattnera0141b92007-07-15 20:42:37 +00006782 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6783 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6784 if (!ShAmt) break;
6785
6786 uint32_t TypeBits = RHSV.getBitWidth();
6787
6788 // Check that the shift amount is in range. If not, don't perform
6789 // undefined shifts. When the shift is visited it will be
6790 // simplified.
6791 if (ShAmt->uge(TypeBits))
6792 break;
6793
6794 if (ICI.isEquality()) {
6795 // If we are comparing against bits always shifted out, the
6796 // comparison cannot succeed.
6797 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006798 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006799 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006800 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6801 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006802 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006803 return ReplaceInstUsesWith(ICI, Cst);
6804 }
6805
6806 if (LHSI->hasOneUse()) {
6807 // Otherwise strength reduce the shift into an and.
6808 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6809 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006810 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006811 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006812
Chris Lattner74381062009-08-30 07:44:24 +00006813 Value *And =
6814 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006815 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006816 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006817 }
6818 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006819
6820 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6821 bool TrueIfSigned = false;
6822 if (LHSI->hasOneUse() &&
6823 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6824 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006825 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006826 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006827 Value *And =
6828 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006829 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006830 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006831 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006832 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006833 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006834
6835 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006836 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006837 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006838 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006839 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006840
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006841 // Check that the shift amount is in range. If not, don't perform
6842 // undefined shifts. When the shift is visited it will be
6843 // simplified.
6844 uint32_t TypeBits = RHSV.getBitWidth();
6845 if (ShAmt->uge(TypeBits))
6846 break;
6847
6848 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006849
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006850 // If we are comparing against bits always shifted out, the
6851 // comparison cannot succeed.
6852 APInt Comp = RHSV << ShAmtVal;
6853 if (LHSI->getOpcode() == Instruction::LShr)
6854 Comp = Comp.lshr(ShAmtVal);
6855 else
6856 Comp = Comp.ashr(ShAmtVal);
6857
6858 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6859 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006860 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006861 return ReplaceInstUsesWith(ICI, Cst);
6862 }
6863
6864 // Otherwise, check to see if the bits shifted out are known to be zero.
6865 // If so, we can compare against the unshifted value:
6866 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006867 if (LHSI->hasOneUse() &&
6868 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006869 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006870 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006871 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006872 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006873
Evan Chengf30752c2008-04-23 00:38:06 +00006874 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006875 // Otherwise strength reduce the shift into an and.
6876 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006877 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006878
Chris Lattner74381062009-08-30 07:44:24 +00006879 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6880 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006881 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006882 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006883 }
6884 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006885 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006886
6887 case Instruction::SDiv:
6888 case Instruction::UDiv:
6889 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6890 // Fold this div into the comparison, producing a range check.
6891 // Determine, based on the divide type, what the range is being
6892 // checked. If there is an overflow on the low or high side, remember
6893 // it, otherwise compute the range [low, hi) bounding the new value.
6894 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006895 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6896 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6897 DivRHS))
6898 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006899 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006900
6901 case Instruction::Add:
6902 // Fold: icmp pred (add, X, C1), C2
6903
6904 if (!ICI.isEquality()) {
6905 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6906 if (!LHSC) break;
6907 const APInt &LHSV = LHSC->getValue();
6908
6909 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6910 .subtract(LHSV);
6911
6912 if (ICI.isSignedPredicate()) {
6913 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006914 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006915 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006916 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006917 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006918 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006919 }
6920 } else {
6921 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006922 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006923 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006924 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006925 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006926 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006927 }
6928 }
6929 }
6930 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006931 }
6932
6933 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6934 if (ICI.isEquality()) {
6935 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6936
6937 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6938 // the second operand is a constant, simplify a bit.
6939 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6940 switch (BO->getOpcode()) {
6941 case Instruction::SRem:
6942 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6943 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6944 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6945 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006946 Value *NewRem =
6947 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6948 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006949 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006950 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006951 }
6952 }
6953 break;
6954 case Instruction::Add:
6955 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6956 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6957 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006958 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006959 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006960 } else if (RHSV == 0) {
6961 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6962 // efficiently invertible, or if the add has just this one use.
6963 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6964
Dan Gohman186a6362009-08-12 16:04:34 +00006965 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006966 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006967 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006968 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006969 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006970 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006971 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006972 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006973 }
6974 }
6975 break;
6976 case Instruction::Xor:
6977 // For the xor case, we can xor two constants together, eliminating
6978 // the explicit xor.
6979 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006980 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006981 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006982
6983 // FALLTHROUGH
6984 case Instruction::Sub:
6985 // Replace (([sub|xor] A, B) != 0) with (A != B)
6986 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006987 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00006988 BO->getOperand(1));
6989 break;
6990
6991 case Instruction::Or:
6992 // If bits are being or'd in that are not present in the constant we
6993 // are comparing against, then the comparison could never succeed!
6994 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006995 Constant *NotCI = ConstantExpr::getNot(RHS);
6996 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00006997 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00006998 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00006999 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007000 }
7001 break;
7002
7003 case Instruction::And:
7004 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7005 // If bits are being compared against that are and'd out, then the
7006 // comparison can never succeed!
7007 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007008 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007009 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007010 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007011
7012 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7013 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007014 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007015 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007016 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007017
7018 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007019 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007020 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007021 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007022 ICmpInst::Predicate pred = isICMP_NE ?
7023 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007024 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007025 }
7026
7027 // ((X & ~7) == 0) --> X < 8
7028 if (RHSV == 0 && isHighOnes(BOC)) {
7029 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007030 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007031 ICmpInst::Predicate pred = isICMP_NE ?
7032 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007033 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007034 }
7035 }
7036 default: break;
7037 }
7038 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7039 // Handle icmp {eq|ne} <intrinsic>, intcst.
7040 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007041 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007042 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007043 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007044 return &ICI;
7045 }
7046 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007047 }
7048 return 0;
7049}
7050
7051/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7052/// We only handle extending casts so far.
7053///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007054Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7055 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007056 Value *LHSCIOp = LHSCI->getOperand(0);
7057 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007058 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007059 Value *RHSCIOp;
7060
Chris Lattner8c756c12007-05-05 22:41:33 +00007061 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7062 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007063 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7064 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007065 cast<IntegerType>(DestTy)->getBitWidth()) {
7066 Value *RHSOp = 0;
7067 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007068 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007069 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7070 RHSOp = RHSC->getOperand(0);
7071 // If the pointer types don't match, insert a bitcast.
7072 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007073 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007074 }
7075
7076 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007077 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007078 }
7079
7080 // The code below only handles extension cast instructions, so far.
7081 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007082 if (LHSCI->getOpcode() != Instruction::ZExt &&
7083 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007084 return 0;
7085
Reid Spencere4d87aa2006-12-23 06:05:41 +00007086 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7087 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007088
Reid Spencere4d87aa2006-12-23 06:05:41 +00007089 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007090 // Not an extension from the same type?
7091 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007092 if (RHSCIOp->getType() != LHSCIOp->getType())
7093 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007094
Nick Lewycky4189a532008-01-28 03:48:02 +00007095 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007096 // and the other is a zext), then we can't handle this.
7097 if (CI->getOpcode() != LHSCI->getOpcode())
7098 return 0;
7099
Nick Lewycky4189a532008-01-28 03:48:02 +00007100 // Deal with equality cases early.
7101 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007102 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007103
7104 // A signed comparison of sign extended values simplifies into a
7105 // signed comparison.
7106 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007107 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007108
7109 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007110 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007111 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007112
Reid Spencere4d87aa2006-12-23 06:05:41 +00007113 // If we aren't dealing with a constant on the RHS, exit early
7114 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7115 if (!CI)
7116 return 0;
7117
7118 // Compute the constant that would happen if we truncated to SrcTy then
7119 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007120 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7121 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007122 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007123
7124 // If the re-extended constant didn't change...
7125 if (Res2 == CI) {
7126 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7127 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007128 // %A = sext i16 %X to i32
7129 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007130 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007131 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007132 // because %A may have negative value.
7133 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007134 // However, we allow this when the compare is EQ/NE, because they are
7135 // signless.
7136 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007137 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007138 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007139 }
7140
7141 // The re-extended constant changed so the constant cannot be represented
7142 // in the shorter type. Consequently, we cannot emit a simple comparison.
7143
7144 // First, handle some easy cases. We know the result cannot be equal at this
7145 // point so handle the ICI.isEquality() cases
7146 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007147 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007148 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007149 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007150
7151 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7152 // should have been folded away previously and not enter in here.
7153 Value *Result;
7154 if (isSignedCmp) {
7155 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007156 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007157 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007158 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007159 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007160 } else {
7161 // We're performing an unsigned comparison.
7162 if (isSignedExt) {
7163 // We're performing an unsigned comp with a sign extended value.
7164 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007165 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007166 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007167 } else {
7168 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007169 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007170 }
7171 }
7172
7173 // Finally, return the value computed.
7174 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007175 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007176 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007177
7178 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7179 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7180 "ICmp should be folded!");
7181 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007182 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007183 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007184}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007185
Reid Spencer832254e2007-02-02 02:16:23 +00007186Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7187 return commonShiftTransforms(I);
7188}
7189
7190Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7191 return commonShiftTransforms(I);
7192}
7193
7194Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007195 if (Instruction *R = commonShiftTransforms(I))
7196 return R;
7197
7198 Value *Op0 = I.getOperand(0);
7199
7200 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7201 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7202 if (CSI->isAllOnesValue())
7203 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007204
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007205 // See if we can turn a signed shr into an unsigned shr.
7206 if (MaskedValueIsZero(Op0,
7207 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7208 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7209
7210 // Arithmetic shifting an all-sign-bit value is a no-op.
7211 unsigned NumSignBits = ComputeNumSignBits(Op0);
7212 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7213 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007214
Chris Lattner348f6652007-12-06 01:59:46 +00007215 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007216}
7217
7218Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7219 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007220 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007221
7222 // shl X, 0 == X and shr X, 0 == X
7223 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007224 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7225 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007226 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007227
Reid Spencere4d87aa2006-12-23 06:05:41 +00007228 if (isa<UndefValue>(Op0)) {
7229 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007230 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007231 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007233 }
7234 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007235 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7236 return ReplaceInstUsesWith(I, Op0);
7237 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007238 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007239 }
7240
Dan Gohman9004c8a2009-05-21 02:28:33 +00007241 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007242 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007243 return &I;
7244
Chris Lattner2eefe512004-04-09 19:05:30 +00007245 // Try to fold constant and into select arguments.
7246 if (isa<Constant>(Op0))
7247 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007248 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007249 return R;
7250
Reid Spencerb83eb642006-10-20 07:07:24 +00007251 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007252 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7253 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007254 return 0;
7255}
7256
Reid Spencerb83eb642006-10-20 07:07:24 +00007257Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007258 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007259 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007260
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007261 // See if we can simplify any instructions used by the instruction whose sole
7262 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007263 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007264
Dan Gohmana119de82009-06-14 23:30:43 +00007265 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7266 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007267 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007268 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007269 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007270 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007271 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007272 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007273 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007274 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007275 }
7276
7277 // ((X*C1) << C2) == (X * (C1 << C2))
7278 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7279 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7280 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007281 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007282 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007283
7284 // Try to fold constant and into select arguments.
7285 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7286 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7287 return R;
7288 if (isa<PHINode>(Op0))
7289 if (Instruction *NV = FoldOpIntoPhi(I))
7290 return NV;
7291
Chris Lattner8999dd32007-12-22 09:07:47 +00007292 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7293 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7294 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7295 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7296 // place. Don't try to do this transformation in this case. Also, we
7297 // require that the input operand is a shift-by-constant so that we have
7298 // confidence that the shifts will get folded together. We could do this
7299 // xform in more cases, but it is unlikely to be profitable.
7300 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7301 isa<ConstantInt>(TrOp->getOperand(1))) {
7302 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007303 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007304 // (shift2 (shift1 & 0x00FF), c2)
7305 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007306
7307 // For logical shifts, the truncation has the effect of making the high
7308 // part of the register be zeros. Emulate this by inserting an AND to
7309 // clear the top bits as needed. This 'and' will usually be zapped by
7310 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007311 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7312 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007313 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7314
7315 // The mask we constructed says what the trunc would do if occurring
7316 // between the shifts. We want to know the effect *after* the second
7317 // shift. We know that it is a logical shift by a constant, so adjust the
7318 // mask as appropriate.
7319 if (I.getOpcode() == Instruction::Shl)
7320 MaskV <<= Op1->getZExtValue();
7321 else {
7322 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7323 MaskV = MaskV.lshr(Op1->getZExtValue());
7324 }
7325
Chris Lattner74381062009-08-30 07:44:24 +00007326 // shift1 & 0x00FF
7327 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7328 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007329
7330 // Return the value truncated to the interesting size.
7331 return new TruncInst(And, I.getType());
7332 }
7333 }
7334
Chris Lattner4d5542c2006-01-06 07:12:35 +00007335 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007336 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7337 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7338 Value *V1, *V2;
7339 ConstantInt *CC;
7340 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007341 default: break;
7342 case Instruction::Add:
7343 case Instruction::And:
7344 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007345 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007346 // These operators commute.
7347 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007348 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007349 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007350 m_Specific(Op1)))) {
7351 Value *YS = // (Y << C)
7352 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7353 // (X + (Y << C))
7354 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7355 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007356 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007357 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007358 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007359 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007360
Chris Lattner150f12a2005-09-18 06:30:59 +00007361 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007362 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007363 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007364 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007365 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007366 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007367 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007368 Value *YS = // (Y << C)
7369 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7370 Op0BO->getName());
7371 // X & (CC << C)
7372 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7373 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007374 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007375 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007376 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007377
Reid Spencera07cb7d2007-02-02 14:41:37 +00007378 // FALL THROUGH.
7379 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007380 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007381 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007382 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007383 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007384 Value *YS = // (Y << C)
7385 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7386 // (X + (Y << C))
7387 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7388 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007389 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007390 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007391 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007392 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007393
Chris Lattner13d4ab42006-05-31 21:14:00 +00007394 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007395 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7396 match(Op0BO->getOperand(0),
7397 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007398 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007399 cast<BinaryOperator>(Op0BO->getOperand(0))
7400 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007401 Value *YS = // (Y << C)
7402 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7403 // X & (CC << C)
7404 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7405 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007406
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007407 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007408 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007409
Chris Lattner11021cb2005-09-18 05:12:10 +00007410 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007411 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007412 }
7413
7414
7415 // If the operand is an bitwise operator with a constant RHS, and the
7416 // shift is the only use, we can pull it out of the shift.
7417 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7418 bool isValid = true; // Valid only for And, Or, Xor
7419 bool highBitSet = false; // Transform if high bit of constant set?
7420
7421 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007422 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007423 case Instruction::Add:
7424 isValid = isLeftShift;
7425 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007426 case Instruction::Or:
7427 case Instruction::Xor:
7428 highBitSet = false;
7429 break;
7430 case Instruction::And:
7431 highBitSet = true;
7432 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007433 }
7434
7435 // If this is a signed shift right, and the high bit is modified
7436 // by the logical operation, do not perform the transformation.
7437 // The highBitSet boolean indicates the value of the high bit of
7438 // the constant which would cause it to be modified for this
7439 // operation.
7440 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007441 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007442 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007443
7444 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007445 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007446
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007447 Value *NewShift =
7448 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007449 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007450
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007451 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007452 NewRHS);
7453 }
7454 }
7455 }
7456 }
7457
Chris Lattnerad0124c2006-01-06 07:52:12 +00007458 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007459 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7460 if (ShiftOp && !ShiftOp->isShift())
7461 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007462
Reid Spencerb83eb642006-10-20 07:07:24 +00007463 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007464 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007465 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7466 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007467 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7468 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7469 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007470
Zhou Sheng4351c642007-04-02 08:20:41 +00007471 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007472
7473 const IntegerType *Ty = cast<IntegerType>(I.getType());
7474
7475 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007476 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007477 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7478 // saturates.
7479 if (AmtSum >= TypeBits) {
7480 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007481 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007482 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7483 }
7484
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007485 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007486 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007487 }
7488
7489 if (ShiftOp->getOpcode() == Instruction::LShr &&
7490 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007491 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007492 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007493
Chris Lattnerb87056f2007-02-05 00:57:54 +00007494 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007495 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007496 }
7497
7498 if (ShiftOp->getOpcode() == Instruction::AShr &&
7499 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007500 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007501 if (AmtSum >= TypeBits)
7502 AmtSum = TypeBits-1;
7503
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007504 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007505
Zhou Shenge9e03f62007-03-28 15:02:20 +00007506 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007507 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007508 }
7509
Chris Lattnerb87056f2007-02-05 00:57:54 +00007510 // Okay, if we get here, one shift must be left, and the other shift must be
7511 // right. See if the amounts are equal.
7512 if (ShiftAmt1 == ShiftAmt2) {
7513 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7514 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007515 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007516 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007517 }
7518 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7519 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007520 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007521 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007522 }
7523 // We can simplify ((X << C) >>s C) into a trunc + sext.
7524 // NOTE: we could do this for any C, but that would make 'unusual' integer
7525 // types. For now, just stick to ones well-supported by the code
7526 // generators.
7527 const Type *SExtType = 0;
7528 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007529 case 1 :
7530 case 8 :
7531 case 16 :
7532 case 32 :
7533 case 64 :
7534 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007535 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007536 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007537 default: break;
7538 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007539 if (SExtType)
7540 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007541 // Otherwise, we can't handle it yet.
7542 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007543 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007544
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007545 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007546 if (I.getOpcode() == Instruction::Shl) {
7547 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7548 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007549 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00007550
Reid Spencer55702aa2007-03-25 21:11:44 +00007551 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007552 return BinaryOperator::CreateAnd(Shift,
7553 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007554 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007555
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007556 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007557 if (I.getOpcode() == Instruction::LShr) {
7558 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007559 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007560
Reid Spencerd5e30f02007-03-26 17:18:58 +00007561 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007562 return BinaryOperator::CreateAnd(Shift,
7563 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00007564 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007565
7566 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7567 } else {
7568 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007569 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007570
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007571 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007572 if (I.getOpcode() == Instruction::Shl) {
7573 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7574 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007575 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7576 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007577
Reid Spencer55702aa2007-03-25 21:11:44 +00007578 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007579 return BinaryOperator::CreateAnd(Shift,
7580 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007581 }
7582
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007583 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007584 if (I.getOpcode() == Instruction::LShr) {
7585 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007586 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007587
Reid Spencer68d27cf2007-03-26 23:45:51 +00007588 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007589 return BinaryOperator::CreateAnd(Shift,
7590 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007591 }
7592
7593 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007594 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007595 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007596 return 0;
7597}
7598
Chris Lattnera1be5662002-05-02 17:06:02 +00007599
Chris Lattnercfd65102005-10-29 04:36:15 +00007600/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7601/// expression. If so, decompose it, returning some value X, such that Val is
7602/// X*Scale+Offset.
7603///
7604static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007605 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007606 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7607 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007608 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007609 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007610 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007611 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007612 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7613 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7614 if (I->getOpcode() == Instruction::Shl) {
7615 // This is a value scaled by '1 << the shift amt'.
7616 Scale = 1U << RHS->getZExtValue();
7617 Offset = 0;
7618 return I->getOperand(0);
7619 } else if (I->getOpcode() == Instruction::Mul) {
7620 // This value is scaled by 'RHS'.
7621 Scale = RHS->getZExtValue();
7622 Offset = 0;
7623 return I->getOperand(0);
7624 } else if (I->getOpcode() == Instruction::Add) {
7625 // We have X+C. Check to see if we really have (X*C2)+C1,
7626 // where C1 is divisible by C2.
7627 unsigned SubScale;
7628 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007629 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7630 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007631 Offset += RHS->getZExtValue();
7632 Scale = SubScale;
7633 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007634 }
7635 }
7636 }
7637
7638 // Otherwise, we can't look past this.
7639 Scale = 1;
7640 Offset = 0;
7641 return Val;
7642}
7643
7644
Chris Lattnerb3f83972005-10-24 06:03:58 +00007645/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7646/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007647Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007648 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007649 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007650
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007651 BuilderTy AllocaBuilder(*Builder);
7652 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7653
Chris Lattnerb53c2382005-10-24 06:22:12 +00007654 // Remove any uses of AI that are dead.
7655 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007656
Chris Lattnerb53c2382005-10-24 06:22:12 +00007657 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7658 Instruction *User = cast<Instruction>(*UI++);
7659 if (isInstructionTriviallyDead(User)) {
7660 while (UI != E && *UI == User)
7661 ++UI; // If this instruction uses AI more than once, don't break UI.
7662
Chris Lattnerb53c2382005-10-24 06:22:12 +00007663 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007664 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007665 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007666 }
7667 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007668
7669 // This requires TargetData to get the alloca alignment and size information.
7670 if (!TD) return 0;
7671
Chris Lattnerb3f83972005-10-24 06:03:58 +00007672 // Get the type really allocated and the type casted to.
7673 const Type *AllocElTy = AI.getAllocatedType();
7674 const Type *CastElTy = PTy->getElementType();
7675 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007676
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007677 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7678 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007679 if (CastElTyAlign < AllocElTyAlign) return 0;
7680
Chris Lattner39387a52005-10-24 06:35:18 +00007681 // If the allocation has multiple uses, only promote it if we are strictly
7682 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007683 // same, we open the door to infinite loops of various kinds. (A reference
7684 // from a dbg.declare doesn't count as a use for this purpose.)
7685 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7686 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007687
Duncan Sands777d2302009-05-09 07:06:46 +00007688 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7689 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007690 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007691
Chris Lattner455fcc82005-10-29 03:19:53 +00007692 // See if we can satisfy the modulus by pulling a scale out of the array
7693 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007694 unsigned ArraySizeScale;
7695 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007696 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007697 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7698 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007699
Chris Lattner455fcc82005-10-29 03:19:53 +00007700 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7701 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007702 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7703 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007704
Chris Lattner455fcc82005-10-29 03:19:53 +00007705 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7706 Value *Amt = 0;
7707 if (Scale == 1) {
7708 Amt = NumElements;
7709 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007710 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007711 // Insert before the alloca, not before the cast.
7712 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007713 }
7714
Jeff Cohen86796be2007-04-04 16:58:57 +00007715 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007716 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007717 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007718 }
7719
Chris Lattnerb3f83972005-10-24 06:03:58 +00007720 AllocationInst *New;
7721 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007722 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007723 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007724 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7725 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007726 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007727
Dale Johannesena0a66372009-03-05 00:39:02 +00007728 // If the allocation has one real use plus a dbg.declare, just remove the
7729 // declare.
7730 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7731 EraseInstFromFunction(*DI);
7732 }
7733 // If the allocation has multiple real uses, insert a cast and change all
7734 // things that used it to use the new cast. This will also hack on CI, but it
7735 // will die soon.
7736 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007737 // New is the allocation instruction, pointer typed. AI is the original
7738 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007739 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007740 AI.replaceAllUsesWith(NewCast);
7741 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007742 return ReplaceInstUsesWith(CI, New);
7743}
7744
Chris Lattner70074e02006-05-13 02:06:03 +00007745/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007746/// and return it as type Ty without inserting any new casts and without
7747/// changing the computed value. This is used by code that tries to decide
7748/// whether promoting or shrinking integer operations to wider or smaller types
7749/// will allow us to eliminate a truncate or extend.
7750///
7751/// This is a truncation operation if Ty is smaller than V->getType(), or an
7752/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007753///
7754/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7755/// should return true if trunc(V) can be computed by computing V in the smaller
7756/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7757/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7758/// efficiently truncated.
7759///
7760/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7761/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7762/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007763bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007764 unsigned CastOpc,
7765 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007766 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007767 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007768 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007769
7770 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007771 if (!I) return false;
7772
Dan Gohman6de29f82009-06-15 22:12:54 +00007773 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007774
Chris Lattner951626b2007-08-02 06:11:14 +00007775 // If this is an extension or truncate, we can often eliminate it.
7776 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7777 // If this is a cast from the destination type, we can trivially eliminate
7778 // it, and this will remove a cast overall.
7779 if (I->getOperand(0)->getType() == Ty) {
7780 // If the first operand is itself a cast, and is eliminable, do not count
7781 // this as an eliminable cast. We would prefer to eliminate those two
7782 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007783 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007784 ++NumCastsRemoved;
7785 return true;
7786 }
7787 }
7788
7789 // We can't extend or shrink something that has multiple uses: doing so would
7790 // require duplicating the instruction in general, which isn't profitable.
7791 if (!I->hasOneUse()) return false;
7792
Evan Chengf35fd542009-01-15 17:01:23 +00007793 unsigned Opc = I->getOpcode();
7794 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007795 case Instruction::Add:
7796 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007797 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007798 case Instruction::And:
7799 case Instruction::Or:
7800 case Instruction::Xor:
7801 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007802 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007803 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007804 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007805 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007806
Eli Friedman070a9812009-07-13 22:46:01 +00007807 case Instruction::UDiv:
7808 case Instruction::URem: {
7809 // UDiv and URem can be truncated if all the truncated bits are zero.
7810 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7811 uint32_t BitWidth = Ty->getScalarSizeInBits();
7812 if (BitWidth < OrigBitWidth) {
7813 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7814 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7815 MaskedValueIsZero(I->getOperand(1), Mask)) {
7816 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7817 NumCastsRemoved) &&
7818 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7819 NumCastsRemoved);
7820 }
7821 }
7822 break;
7823 }
Chris Lattner46b96052006-11-29 07:18:39 +00007824 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007825 // If we are truncating the result of this SHL, and if it's a shift of a
7826 // constant amount, we can always perform a SHL in a smaller type.
7827 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007828 uint32_t BitWidth = Ty->getScalarSizeInBits();
7829 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007830 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007831 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007832 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007833 }
7834 break;
7835 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007836 // If this is a truncate of a logical shr, we can truncate it to a smaller
7837 // lshr iff we know that the bits we would otherwise be shifting in are
7838 // already zeros.
7839 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007840 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7841 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007842 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007843 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007844 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7845 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007846 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007847 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007848 }
7849 }
Chris Lattner46b96052006-11-29 07:18:39 +00007850 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007851 case Instruction::ZExt:
7852 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007853 case Instruction::Trunc:
7854 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007855 // can safely replace it. Note that replacing it does not reduce the number
7856 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007857 if (Opc == CastOpc)
7858 return true;
7859
7860 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007861 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007862 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007863 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007864 case Instruction::Select: {
7865 SelectInst *SI = cast<SelectInst>(I);
7866 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007867 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007868 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007869 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007870 }
Chris Lattner8114b712008-06-18 04:00:49 +00007871 case Instruction::PHI: {
7872 // We can change a phi if we can change all operands.
7873 PHINode *PN = cast<PHINode>(I);
7874 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7875 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007876 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007877 return false;
7878 return true;
7879 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007880 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007881 // TODO: Can handle more cases here.
7882 break;
7883 }
7884
7885 return false;
7886}
7887
7888/// EvaluateInDifferentType - Given an expression that
7889/// CanEvaluateInDifferentType returns true for, actually insert the code to
7890/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007891Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007892 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007893 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007894 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007895 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007896
7897 // Otherwise, it must be an instruction.
7898 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007899 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007900 unsigned Opc = I->getOpcode();
7901 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007902 case Instruction::Add:
7903 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007904 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007905 case Instruction::And:
7906 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007907 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007908 case Instruction::AShr:
7909 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007910 case Instruction::Shl:
7911 case Instruction::UDiv:
7912 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007913 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007914 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007915 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007916 break;
7917 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007918 case Instruction::Trunc:
7919 case Instruction::ZExt:
7920 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007921 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007922 // just return the source. There's no need to insert it because it is not
7923 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007924 if (I->getOperand(0)->getType() == Ty)
7925 return I->getOperand(0);
7926
Chris Lattner8114b712008-06-18 04:00:49 +00007927 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007928 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007929 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007930 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007931 case Instruction::Select: {
7932 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7933 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7934 Res = SelectInst::Create(I->getOperand(0), True, False);
7935 break;
7936 }
Chris Lattner8114b712008-06-18 04:00:49 +00007937 case Instruction::PHI: {
7938 PHINode *OPN = cast<PHINode>(I);
7939 PHINode *NPN = PHINode::Create(Ty);
7940 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7941 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7942 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7943 }
7944 Res = NPN;
7945 break;
7946 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007947 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007948 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007949 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007950 break;
7951 }
7952
Chris Lattner8114b712008-06-18 04:00:49 +00007953 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007954 return InsertNewInstBefore(Res, *I);
7955}
7956
Reid Spencer3da59db2006-11-27 01:05:10 +00007957/// @brief Implement the transforms common to all CastInst visitors.
7958Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007959 Value *Src = CI.getOperand(0);
7960
Dan Gohman23d9d272007-05-11 21:10:54 +00007961 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007962 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007963 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007964 if (Instruction::CastOps opc =
7965 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7966 // The first cast (CSrc) is eliminable so we need to fix up or replace
7967 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007968 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007969 }
7970 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007971
Reid Spencer3da59db2006-11-27 01:05:10 +00007972 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00007973 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7974 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7975 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00007976
7977 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00007978 if (isa<PHINode>(Src))
7979 if (Instruction *NV = FoldOpIntoPhi(CI))
7980 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00007981
Reid Spencer3da59db2006-11-27 01:05:10 +00007982 return 0;
7983}
7984
Chris Lattner46cd5a12009-01-09 05:44:56 +00007985/// FindElementAtOffset - Given a type and a constant offset, determine whether
7986/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00007987/// the specified offset. If so, fill them into NewIndices and return the
7988/// resultant element type, otherwise return null.
7989static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7990 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00007991 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007992 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007993 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00007994 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00007995
7996 // Start with the index over the outer type. Note that the type size
7997 // might be zero (even if the offset isn't zero) if the indexed type
7998 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00007999 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008000 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008001 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008002 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008003 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008004
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008005 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008006 if (Offset < 0) {
8007 --FirstIdx;
8008 Offset += TySize;
8009 assert(Offset >= 0);
8010 }
8011 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8012 }
8013
Owen Andersoneed707b2009-07-24 23:12:02 +00008014 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008015
8016 // Index into the types. If we fail, set OrigBase to null.
8017 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008018 // Indexing into tail padding between struct/array elements.
8019 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008020 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008021
Chris Lattner46cd5a12009-01-09 05:44:56 +00008022 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8023 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008024 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8025 "Offset must stay within the indexed type");
8026
Chris Lattner46cd5a12009-01-09 05:44:56 +00008027 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008028 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008029
8030 Offset -= SL->getElementOffset(Elt);
8031 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008032 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008033 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008034 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008035 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008036 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008037 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008038 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008039 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008040 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008041 }
8042 }
8043
Chris Lattner3914f722009-01-24 01:00:13 +00008044 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008045}
8046
Chris Lattnerd3e28342007-04-27 17:44:50 +00008047/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8048Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8049 Value *Src = CI.getOperand(0);
8050
Chris Lattnerd3e28342007-04-27 17:44:50 +00008051 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008052 // If casting the result of a getelementptr instruction with no offset, turn
8053 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008054 if (GEP->hasAllZeroIndices()) {
8055 // Changing the cast operand is usually not a good idea but it is safe
8056 // here because the pointer operand is being replaced with another
8057 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008058 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008059 CI.setOperand(0, GEP->getOperand(0));
8060 return &CI;
8061 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008062
8063 // If the GEP has a single use, and the base pointer is a bitcast, and the
8064 // GEP computes a constant offset, see if we can convert these three
8065 // instructions into fewer. This typically happens with unions and other
8066 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008067 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008068 if (GEP->hasAllConstantIndices()) {
8069 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008070 ConstantInt *OffsetV =
8071 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008072 int64_t Offset = OffsetV->getSExtValue();
8073
8074 // Get the base pointer input of the bitcast, and the type it points to.
8075 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8076 const Type *GEPIdxTy =
8077 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008078 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008079 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008080 // If we were able to index down into an element, create the GEP
8081 // and bitcast the result. This eliminates one bitcast, potentially
8082 // two.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008083 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8084 NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008085 NGEP->takeName(GEP);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008086 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008087 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008088
Chris Lattner46cd5a12009-01-09 05:44:56 +00008089 if (isa<BitCastInst>(CI))
8090 return new BitCastInst(NGEP, CI.getType());
8091 assert(isa<PtrToIntInst>(CI));
8092 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008093 }
8094 }
8095 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008096 }
8097
8098 return commonCastTransforms(CI);
8099}
8100
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008101/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8102/// type like i42. We don't want to introduce operations on random non-legal
8103/// integer types where they don't already exist in the code. In the future,
8104/// we should consider making this based off target-data, so that 32-bit targets
8105/// won't get i64 operations etc.
8106static bool isSafeIntegerType(const Type *Ty) {
8107 switch (Ty->getPrimitiveSizeInBits()) {
8108 case 8:
8109 case 16:
8110 case 32:
8111 case 64:
8112 return true;
8113 default:
8114 return false;
8115 }
8116}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008117
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008118/// commonIntCastTransforms - This function implements the common transforms
8119/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008120Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8121 if (Instruction *Result = commonCastTransforms(CI))
8122 return Result;
8123
8124 Value *Src = CI.getOperand(0);
8125 const Type *SrcTy = Src->getType();
8126 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008127 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8128 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008129
Reid Spencer3da59db2006-11-27 01:05:10 +00008130 // See if we can simplify any instructions used by the LHS whose sole
8131 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008132 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008133 return &CI;
8134
8135 // If the source isn't an instruction or has more than one use then we
8136 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008137 Instruction *SrcI = dyn_cast<Instruction>(Src);
8138 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008139 return 0;
8140
Chris Lattnerc739cd62007-03-03 05:27:34 +00008141 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008142 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008143 // Only do this if the dest type is a simple type, don't convert the
8144 // expression tree to something weird like i93 unless the source is also
8145 // strange.
8146 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008147 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8148 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008149 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008150 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008151 // eliminates the cast, so it is always a win. If this is a zero-extension,
8152 // we need to do an AND to maintain the clear top-part of the computation,
8153 // so we require that the input have eliminated at least one cast. If this
8154 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008155 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008156 bool DoXForm = false;
8157 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008158 switch (CI.getOpcode()) {
8159 default:
8160 // All the others use floating point so we shouldn't actually
8161 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008162 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008163 case Instruction::Trunc:
8164 DoXForm = true;
8165 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008166 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008167 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008168 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008169 // If it's unnecessary to issue an AND to clear the high bits, it's
8170 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008171 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008172 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8173 if (MaskedValueIsZero(TryRes, Mask))
8174 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008175
8176 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008177 if (TryI->use_empty())
8178 EraseInstFromFunction(*TryI);
8179 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008180 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008181 }
Evan Chengf35fd542009-01-15 17:01:23 +00008182 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008183 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008184 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008185 // If we do not have to emit the truncate + sext pair, then it's always
8186 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008187 //
8188 // It's not safe to eliminate the trunc + sext pair if one of the
8189 // eliminated cast is a truncate. e.g.
8190 // t2 = trunc i32 t1 to i16
8191 // t3 = sext i16 t2 to i32
8192 // !=
8193 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008194 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008195 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8196 if (NumSignBits > (DestBitSize - SrcBitSize))
8197 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008198
8199 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008200 if (TryI->use_empty())
8201 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008202 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008203 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008204 }
Evan Chengf35fd542009-01-15 17:01:23 +00008205 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008206
8207 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008208 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8209 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008210 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8211 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008212 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008213 // Just replace this cast with the result.
8214 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008215
Reid Spencer3da59db2006-11-27 01:05:10 +00008216 assert(Res->getType() == DestTy);
8217 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008218 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008219 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008220 // Just replace this cast with the result.
8221 return ReplaceInstUsesWith(CI, Res);
8222 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008223 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008224
8225 // If the high bits are already zero, just replace this cast with the
8226 // result.
8227 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8228 if (MaskedValueIsZero(Res, Mask))
8229 return ReplaceInstUsesWith(CI, Res);
8230
8231 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008232 Constant *C = ConstantInt::get(*Context,
8233 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008234 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008235 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008236 case Instruction::SExt: {
8237 // If the high bits are already filled with sign bit, just replace this
8238 // cast with the result.
8239 unsigned NumSignBits = ComputeNumSignBits(Res);
8240 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008241 return ReplaceInstUsesWith(CI, Res);
8242
Reid Spencer3da59db2006-11-27 01:05:10 +00008243 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008244 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008245 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008246 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008247 }
8248 }
8249
8250 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8251 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8252
8253 switch (SrcI->getOpcode()) {
8254 case Instruction::Add:
8255 case Instruction::Mul:
8256 case Instruction::And:
8257 case Instruction::Or:
8258 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008259 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008260 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8261 // Don't insert two casts unless at least one can be eliminated.
8262 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008263 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008264 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8265 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008266 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008267 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008268 }
8269 }
8270
8271 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8272 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8273 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008274 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008275 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008276 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008277 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008278 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008279 }
8280 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008281
Eli Friedman65445c52009-07-13 21:45:57 +00008282 case Instruction::Shl: {
8283 // Canonicalize trunc inside shl, if we can.
8284 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8285 if (CI && DestBitSize < SrcBitSize &&
8286 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008287 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8288 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008289 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008290 }
8291 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008292 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008293 }
8294 return 0;
8295}
8296
Chris Lattner8a9f5712007-04-11 06:57:46 +00008297Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008298 if (Instruction *Result = commonIntCastTransforms(CI))
8299 return Result;
8300
8301 Value *Src = CI.getOperand(0);
8302 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008303 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8304 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008305
8306 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008307 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008308 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008309 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008310 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008311 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008312 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008313
Chris Lattner4f9797d2009-03-24 18:15:30 +00008314 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8315 ConstantInt *ShAmtV = 0;
8316 Value *ShiftOp = 0;
8317 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008318 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008319 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8320
8321 // Get a mask for the bits shifting in.
8322 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8323 if (MaskedValueIsZero(ShiftOp, Mask)) {
8324 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008325 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008326
8327 // Okay, we can shrink this. Truncate the input, then return a new
8328 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008329 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008330 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008331 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008332 }
8333 }
8334
8335 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008336}
8337
Evan Chengb98a10e2008-03-24 00:21:34 +00008338/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8339/// in order to eliminate the icmp.
8340Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8341 bool DoXform) {
8342 // If we are just checking for a icmp eq of a single bit and zext'ing it
8343 // to an integer, then shift the bit to the appropriate place and then
8344 // cast to integer to avoid the comparison.
8345 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8346 const APInt &Op1CV = Op1C->getValue();
8347
8348 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8349 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8350 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8351 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8352 if (!DoXform) return ICI;
8353
8354 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008355 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008356 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008357 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008358 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008359 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008360
8361 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008362 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008363 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008364 }
8365
8366 return ReplaceInstUsesWith(CI, In);
8367 }
8368
8369
8370
8371 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8372 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8373 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8374 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8375 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8376 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8377 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8378 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8379 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8380 // This only works for EQ and NE
8381 ICI->isEquality()) {
8382 // If Op1C some other power of two, convert:
8383 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8384 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8385 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8386 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8387
8388 APInt KnownZeroMask(~KnownZero);
8389 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8390 if (!DoXform) return ICI;
8391
8392 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8393 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8394 // (X&4) == 2 --> false
8395 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008396 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008397 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008398 return ReplaceInstUsesWith(CI, Res);
8399 }
8400
8401 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8402 Value *In = ICI->getOperand(0);
8403 if (ShiftAmt) {
8404 // Perform a logical shr by shiftamt.
8405 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008406 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8407 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008408 }
8409
8410 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008411 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008412 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008413 }
8414
8415 if (CI.getType() == In->getType())
8416 return ReplaceInstUsesWith(CI, In);
8417 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008418 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008419 }
8420 }
8421 }
8422
8423 return 0;
8424}
8425
Chris Lattner8a9f5712007-04-11 06:57:46 +00008426Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008427 // If one of the common conversion will work ..
8428 if (Instruction *Result = commonIntCastTransforms(CI))
8429 return Result;
8430
8431 Value *Src = CI.getOperand(0);
8432
Chris Lattnera84f47c2009-02-17 20:47:23 +00008433 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8434 // types and if the sizes are just right we can convert this into a logical
8435 // 'and' which will be much cheaper than the pair of casts.
8436 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8437 // Get the sizes of the types involved. We know that the intermediate type
8438 // will be smaller than A or C, but don't know the relation between A and C.
8439 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008440 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8441 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8442 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008443 // If we're actually extending zero bits, then if
8444 // SrcSize < DstSize: zext(a & mask)
8445 // SrcSize == DstSize: a & mask
8446 // SrcSize > DstSize: trunc(a) & mask
8447 if (SrcSize < DstSize) {
8448 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008449 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008450 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008451 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008452 }
8453
8454 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008455 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008456 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008457 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008458 }
8459 if (SrcSize > DstSize) {
8460 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008461 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008462 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008463 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008464 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008465 }
8466 }
8467
Evan Chengb98a10e2008-03-24 00:21:34 +00008468 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8469 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008470
Evan Chengb98a10e2008-03-24 00:21:34 +00008471 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8472 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8473 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8474 // of the (zext icmp) will be transformed.
8475 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8476 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8477 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8478 (transformZExtICmp(LHS, CI, false) ||
8479 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008480 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8481 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008482 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008483 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008484 }
8485
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008486 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008487 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8488 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8489 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8490 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008491 if (TI0->getType() == CI.getType())
8492 return
8493 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008494 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008495 }
8496
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008497 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8498 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8499 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8500 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8501 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8502 And->getOperand(1) == C)
8503 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8504 Value *TI0 = TI->getOperand(0);
8505 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008506 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008507 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008508 return BinaryOperator::CreateXor(NewAnd, ZC);
8509 }
8510 }
8511
Reid Spencer3da59db2006-11-27 01:05:10 +00008512 return 0;
8513}
8514
Chris Lattner8a9f5712007-04-11 06:57:46 +00008515Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008516 if (Instruction *I = commonIntCastTransforms(CI))
8517 return I;
8518
Chris Lattner8a9f5712007-04-11 06:57:46 +00008519 Value *Src = CI.getOperand(0);
8520
Dan Gohman1975d032008-10-30 20:40:10 +00008521 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008522 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008523 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008524 Constant::getAllOnesValue(CI.getType()),
8525 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008526
8527 // See if the value being truncated is already sign extended. If so, just
8528 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008529 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008530 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008531 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8532 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8533 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008534 unsigned NumSignBits = ComputeNumSignBits(Op);
8535
8536 if (OpBits == DestBits) {
8537 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8538 // bits, it is already ready.
8539 if (NumSignBits > DestBits-MidBits)
8540 return ReplaceInstUsesWith(CI, Op);
8541 } else if (OpBits < DestBits) {
8542 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8543 // bits, just sext from i32.
8544 if (NumSignBits > OpBits-MidBits)
8545 return new SExtInst(Op, CI.getType(), "tmp");
8546 } else {
8547 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8548 // bits, just truncate to i32.
8549 if (NumSignBits > OpBits-MidBits)
8550 return new TruncInst(Op, CI.getType(), "tmp");
8551 }
8552 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008553
8554 // If the input is a shl/ashr pair of a same constant, then this is a sign
8555 // extension from a smaller value. If we could trust arbitrary bitwidth
8556 // integers, we could turn this into a truncate to the smaller bit and then
8557 // use a sext for the whole extension. Since we don't, look deeper and check
8558 // for a truncate. If the source and dest are the same type, eliminate the
8559 // trunc and extend and just do shifts. For example, turn:
8560 // %a = trunc i32 %i to i8
8561 // %b = shl i8 %a, 6
8562 // %c = ashr i8 %b, 6
8563 // %d = sext i8 %c to i32
8564 // into:
8565 // %a = shl i32 %i, 30
8566 // %d = ashr i32 %a, 30
8567 Value *A = 0;
8568 ConstantInt *BA = 0, *CA = 0;
8569 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008570 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008571 BA == CA && isa<TruncInst>(A)) {
8572 Value *I = cast<TruncInst>(A)->getOperand(0);
8573 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008574 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8575 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008576 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008577 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008578 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008579 return BinaryOperator::CreateAShr(I, ShAmtV);
8580 }
8581 }
8582
Chris Lattnerba417832007-04-11 06:12:58 +00008583 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008584}
8585
Chris Lattnerb7530652008-01-27 05:29:54 +00008586/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8587/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008588static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008589 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008590 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008591 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008592 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8593 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008594 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008595 return 0;
8596}
8597
8598/// LookThroughFPExtensions - If this is an fp extension instruction, look
8599/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008600static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008601 if (Instruction *I = dyn_cast<Instruction>(V))
8602 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008603 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008604
8605 // If this value is a constant, return the constant in the smallest FP type
8606 // that can accurately represent it. This allows us to turn
8607 // (float)((double)X+2.0) into x+2.0f.
8608 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008609 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008610 return V; // No constant folding of this.
8611 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008612 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008613 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008614 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008615 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008616 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008617 return V;
8618 // Don't try to shrink to various long double types.
8619 }
8620
8621 return V;
8622}
8623
8624Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8625 if (Instruction *I = commonCastTransforms(CI))
8626 return I;
8627
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008628 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008629 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008630 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008631 // many builtins (sqrt, etc).
8632 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8633 if (OpI && OpI->hasOneUse()) {
8634 switch (OpI->getOpcode()) {
8635 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008636 case Instruction::FAdd:
8637 case Instruction::FSub:
8638 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008639 case Instruction::FDiv:
8640 case Instruction::FRem:
8641 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008642 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8643 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008644 if (LHSTrunc->getType() != SrcTy &&
8645 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008646 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008647 // If the source types were both smaller than the destination type of
8648 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008649 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8650 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008651 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8652 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008653 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008654 }
8655 }
8656 break;
8657 }
8658 }
8659 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008660}
8661
8662Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8663 return commonCastTransforms(CI);
8664}
8665
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008666Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008667 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8668 if (OpI == 0)
8669 return commonCastTransforms(FI);
8670
8671 // fptoui(uitofp(X)) --> X
8672 // fptoui(sitofp(X)) --> X
8673 // This is safe if the intermediate type has enough bits in its mantissa to
8674 // accurately represent all values of X. For example, do not do this with
8675 // i64->float->i64. This is also safe for sitofp case, because any negative
8676 // 'X' value would cause an undefined result for the fptoui.
8677 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8678 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008679 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008680 OpI->getType()->getFPMantissaWidth())
8681 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008682
8683 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008684}
8685
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008686Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008687 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8688 if (OpI == 0)
8689 return commonCastTransforms(FI);
8690
8691 // fptosi(sitofp(X)) --> X
8692 // fptosi(uitofp(X)) --> X
8693 // This is safe if the intermediate type has enough bits in its mantissa to
8694 // accurately represent all values of X. For example, do not do this with
8695 // i64->float->i64. This is also safe for sitofp case, because any negative
8696 // 'X' value would cause an undefined result for the fptoui.
8697 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8698 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008699 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008700 OpI->getType()->getFPMantissaWidth())
8701 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008702
8703 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008704}
8705
8706Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8707 return commonCastTransforms(CI);
8708}
8709
8710Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8711 return commonCastTransforms(CI);
8712}
8713
Chris Lattnera0e69692009-03-24 18:35:40 +00008714Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8715 // If the destination integer type is smaller than the intptr_t type for
8716 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8717 // trunc to be exposed to other transforms. Don't do this for extending
8718 // ptrtoint's, because we don't know if the target sign or zero extends its
8719 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008720 if (TD &&
8721 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008722 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8723 TD->getIntPtrType(CI.getContext()),
8724 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008725 return new TruncInst(P, CI.getType());
8726 }
8727
Chris Lattnerd3e28342007-04-27 17:44:50 +00008728 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008729}
8730
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008731Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008732 // If the source integer type is larger than the intptr_t type for
8733 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8734 // allows the trunc to be exposed to other transforms. Don't do this for
8735 // extending inttoptr's, because we don't know if the target sign or zero
8736 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008737 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008738 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008739 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8740 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008741 return new IntToPtrInst(P, CI.getType());
8742 }
8743
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008744 if (Instruction *I = commonCastTransforms(CI))
8745 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008746
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008747 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008748}
8749
Chris Lattnerd3e28342007-04-27 17:44:50 +00008750Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008751 // If the operands are integer typed then apply the integer transforms,
8752 // otherwise just apply the common ones.
8753 Value *Src = CI.getOperand(0);
8754 const Type *SrcTy = Src->getType();
8755 const Type *DestTy = CI.getType();
8756
Eli Friedman7e25d452009-07-13 20:53:00 +00008757 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008758 if (Instruction *I = commonPointerCastTransforms(CI))
8759 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008760 } else {
8761 if (Instruction *Result = commonCastTransforms(CI))
8762 return Result;
8763 }
8764
8765
8766 // Get rid of casts from one type to the same type. These are useless and can
8767 // be replaced by the operand.
8768 if (DestTy == Src->getType())
8769 return ReplaceInstUsesWith(CI, Src);
8770
Reid Spencer3da59db2006-11-27 01:05:10 +00008771 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008772 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8773 const Type *DstElTy = DstPTy->getElementType();
8774 const Type *SrcElTy = SrcPTy->getElementType();
8775
Nate Begeman83ad90a2008-03-31 00:22:16 +00008776 // If the address spaces don't match, don't eliminate the bitcast, which is
8777 // required for changing types.
8778 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8779 return 0;
8780
Chris Lattnerd3e28342007-04-27 17:44:50 +00008781 // If we are casting a malloc or alloca to a pointer to a type of the same
8782 // size, rewrite the allocation instruction to allocate the "right" type.
8783 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8784 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8785 return V;
8786
Chris Lattnerd717c182007-05-05 22:32:24 +00008787 // If the source and destination are pointers, and this cast is equivalent
8788 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008789 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008790 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008791 unsigned NumZeros = 0;
8792 while (SrcElTy != DstElTy &&
8793 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8794 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8795 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8796 ++NumZeros;
8797 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008798
Chris Lattnerd3e28342007-04-27 17:44:50 +00008799 // If we found a path from the src to dest, create the getelementptr now.
8800 if (SrcElTy == DstElTy) {
8801 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008802 Instruction *GEP = GetElementPtrInst::Create(Src,
8803 Idxs.begin(), Idxs.end(), "",
8804 ((Instruction*) NULL));
8805 cast<GEPOperator>(GEP)->setIsInBounds(true);
8806 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008807 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008808 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008809
Eli Friedman2451a642009-07-18 23:06:53 +00008810 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8811 if (DestVTy->getNumElements() == 1) {
8812 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008813 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008814 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00008815 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008816 }
8817 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8818 }
8819 }
8820
8821 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8822 if (SrcVTy->getNumElements() == 1) {
8823 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008824 Value *Elem =
8825 Builder->CreateExtractElement(Src,
8826 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008827 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8828 }
8829 }
8830 }
8831
Reid Spencer3da59db2006-11-27 01:05:10 +00008832 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8833 if (SVI->hasOneUse()) {
8834 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8835 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008836 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008837 cast<VectorType>(DestTy)->getNumElements() ==
8838 SVI->getType()->getNumElements() &&
8839 SVI->getType()->getNumElements() ==
8840 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008841 CastInst *Tmp;
8842 // If either of the operands is a cast from CI.getType(), then
8843 // evaluating the shuffle in the casted destination's type will allow
8844 // us to eliminate at least one cast.
8845 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8846 Tmp->getOperand(0)->getType() == DestTy) ||
8847 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8848 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008849 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8850 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008851 // Return a new shuffle vector. Use the same element ID's, as we
8852 // know the vector types match #elts.
8853 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008854 }
8855 }
8856 }
8857 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008858 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008859}
8860
Chris Lattnere576b912004-04-09 23:46:01 +00008861/// GetSelectFoldableOperands - We want to turn code that looks like this:
8862/// %C = or %A, %B
8863/// %D = select %cond, %C, %A
8864/// into:
8865/// %C = select %cond, %B, 0
8866/// %D = or %A, %C
8867///
8868/// Assuming that the specified instruction is an operand to the select, return
8869/// a bitmask indicating which operands of this instruction are foldable if they
8870/// equal the other incoming value of the select.
8871///
8872static unsigned GetSelectFoldableOperands(Instruction *I) {
8873 switch (I->getOpcode()) {
8874 case Instruction::Add:
8875 case Instruction::Mul:
8876 case Instruction::And:
8877 case Instruction::Or:
8878 case Instruction::Xor:
8879 return 3; // Can fold through either operand.
8880 case Instruction::Sub: // Can only fold on the amount subtracted.
8881 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008882 case Instruction::LShr:
8883 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008884 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008885 default:
8886 return 0; // Cannot fold
8887 }
8888}
8889
8890/// GetSelectFoldableConstant - For the same transformation as the previous
8891/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008892static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008893 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008894 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008895 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008896 case Instruction::Add:
8897 case Instruction::Sub:
8898 case Instruction::Or:
8899 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008900 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008901 case Instruction::LShr:
8902 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008903 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008904 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008905 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008906 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008907 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008908 }
8909}
8910
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008911/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8912/// have the same opcode and only one use each. Try to simplify this.
8913Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8914 Instruction *FI) {
8915 if (TI->getNumOperands() == 1) {
8916 // If this is a non-volatile load or a cast from the same type,
8917 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008918 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008919 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8920 return 0;
8921 } else {
8922 return 0; // unknown unary op.
8923 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008924
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008925 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008926 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008927 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008928 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008929 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008930 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008931 }
8932
Reid Spencer832254e2007-02-02 02:16:23 +00008933 // Only handle binary operators here.
8934 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008935 return 0;
8936
8937 // Figure out if the operations have any operands in common.
8938 Value *MatchOp, *OtherOpT, *OtherOpF;
8939 bool MatchIsOpZero;
8940 if (TI->getOperand(0) == FI->getOperand(0)) {
8941 MatchOp = TI->getOperand(0);
8942 OtherOpT = TI->getOperand(1);
8943 OtherOpF = FI->getOperand(1);
8944 MatchIsOpZero = true;
8945 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8946 MatchOp = TI->getOperand(1);
8947 OtherOpT = TI->getOperand(0);
8948 OtherOpF = FI->getOperand(0);
8949 MatchIsOpZero = false;
8950 } else if (!TI->isCommutative()) {
8951 return 0;
8952 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8953 MatchOp = TI->getOperand(0);
8954 OtherOpT = TI->getOperand(1);
8955 OtherOpF = FI->getOperand(0);
8956 MatchIsOpZero = true;
8957 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8958 MatchOp = TI->getOperand(1);
8959 OtherOpT = TI->getOperand(0);
8960 OtherOpF = FI->getOperand(1);
8961 MatchIsOpZero = true;
8962 } else {
8963 return 0;
8964 }
8965
8966 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00008967 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8968 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008969 InsertNewInstBefore(NewSI, SI);
8970
8971 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8972 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008973 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008974 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008975 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008976 }
Torok Edwinc23197a2009-07-14 16:55:14 +00008977 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00008978 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008979}
8980
Evan Chengde621922009-03-31 20:42:45 +00008981static bool isSelect01(Constant *C1, Constant *C2) {
8982 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8983 if (!C1I)
8984 return false;
8985 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8986 if (!C2I)
8987 return false;
8988 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8989}
8990
8991/// FoldSelectIntoOp - Try fold the select into one of the operands to
8992/// facilitate further optimization.
8993Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8994 Value *FalseVal) {
8995 // See the comment above GetSelectFoldableOperands for a description of the
8996 // transformation we are doing here.
8997 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
8998 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8999 !isa<Constant>(FalseVal)) {
9000 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9001 unsigned OpToFold = 0;
9002 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9003 OpToFold = 1;
9004 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9005 OpToFold = 2;
9006 }
9007
9008 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009009 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009010 Value *OOp = TVI->getOperand(2-OpToFold);
9011 // Avoid creating select between 2 constants unless it's selecting
9012 // between 0 and 1.
9013 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9014 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9015 InsertNewInstBefore(NewSel, SI);
9016 NewSel->takeName(TVI);
9017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9018 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009019 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009020 }
9021 }
9022 }
9023 }
9024 }
9025
9026 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9027 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9028 !isa<Constant>(TrueVal)) {
9029 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9030 unsigned OpToFold = 0;
9031 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9032 OpToFold = 1;
9033 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9034 OpToFold = 2;
9035 }
9036
9037 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009038 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009039 Value *OOp = FVI->getOperand(2-OpToFold);
9040 // Avoid creating select between 2 constants unless it's selecting
9041 // between 0 and 1.
9042 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9043 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9044 InsertNewInstBefore(NewSel, SI);
9045 NewSel->takeName(FVI);
9046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9047 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009048 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009049 }
9050 }
9051 }
9052 }
9053 }
9054
9055 return 0;
9056}
9057
Dan Gohman81b28ce2008-09-16 18:46:06 +00009058/// visitSelectInstWithICmp - Visit a SelectInst that has an
9059/// ICmpInst as its first operand.
9060///
9061Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9062 ICmpInst *ICI) {
9063 bool Changed = false;
9064 ICmpInst::Predicate Pred = ICI->getPredicate();
9065 Value *CmpLHS = ICI->getOperand(0);
9066 Value *CmpRHS = ICI->getOperand(1);
9067 Value *TrueVal = SI.getTrueValue();
9068 Value *FalseVal = SI.getFalseValue();
9069
9070 // Check cases where the comparison is with a constant that
9071 // can be adjusted to fit the min/max idiom. We may edit ICI in
9072 // place here, so make sure the select is the only user.
9073 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009074 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009075 switch (Pred) {
9076 default: break;
9077 case ICmpInst::ICMP_ULT:
9078 case ICmpInst::ICMP_SLT: {
9079 // X < MIN ? T : F --> F
9080 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9081 return ReplaceInstUsesWith(SI, FalseVal);
9082 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009083 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009084 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9085 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9086 Pred = ICmpInst::getSwappedPredicate(Pred);
9087 CmpRHS = AdjustedRHS;
9088 std::swap(FalseVal, TrueVal);
9089 ICI->setPredicate(Pred);
9090 ICI->setOperand(1, CmpRHS);
9091 SI.setOperand(1, TrueVal);
9092 SI.setOperand(2, FalseVal);
9093 Changed = true;
9094 }
9095 break;
9096 }
9097 case ICmpInst::ICMP_UGT:
9098 case ICmpInst::ICMP_SGT: {
9099 // X > MAX ? T : F --> F
9100 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9101 return ReplaceInstUsesWith(SI, FalseVal);
9102 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009103 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009104 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9105 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9106 Pred = ICmpInst::getSwappedPredicate(Pred);
9107 CmpRHS = AdjustedRHS;
9108 std::swap(FalseVal, TrueVal);
9109 ICI->setPredicate(Pred);
9110 ICI->setOperand(1, CmpRHS);
9111 SI.setOperand(1, TrueVal);
9112 SI.setOperand(2, FalseVal);
9113 Changed = true;
9114 }
9115 break;
9116 }
9117 }
9118
Dan Gohman1975d032008-10-30 20:40:10 +00009119 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9120 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009121 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009122 if (match(TrueVal, m_ConstantInt<-1>()) &&
9123 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009124 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009125 else if (match(TrueVal, m_ConstantInt<0>()) &&
9126 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009127 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9128
Dan Gohman1975d032008-10-30 20:40:10 +00009129 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9130 // If we are just checking for a icmp eq of a single bit and zext'ing it
9131 // to an integer, then shift the bit to the appropriate place and then
9132 // cast to integer to avoid the comparison.
9133 const APInt &Op1CV = CI->getValue();
9134
9135 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9136 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9137 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009138 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009139 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009140 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009141 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009142 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009143 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009144 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009145 if (In->getType() != SI.getType())
9146 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009147 true/*SExt*/, "tmp", ICI);
9148
9149 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009150 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009151 In->getName()+".not"), *ICI);
9152
9153 return ReplaceInstUsesWith(SI, In);
9154 }
9155 }
9156 }
9157
Dan Gohman81b28ce2008-09-16 18:46:06 +00009158 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9159 // Transform (X == Y) ? X : Y -> Y
9160 if (Pred == ICmpInst::ICMP_EQ)
9161 return ReplaceInstUsesWith(SI, FalseVal);
9162 // Transform (X != Y) ? X : Y -> X
9163 if (Pred == ICmpInst::ICMP_NE)
9164 return ReplaceInstUsesWith(SI, TrueVal);
9165 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9166
9167 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9168 // Transform (X == Y) ? Y : X -> X
9169 if (Pred == ICmpInst::ICMP_EQ)
9170 return ReplaceInstUsesWith(SI, FalseVal);
9171 // Transform (X != Y) ? Y : X -> Y
9172 if (Pred == ICmpInst::ICMP_NE)
9173 return ReplaceInstUsesWith(SI, TrueVal);
9174 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9175 }
9176
9177 /// NOTE: if we wanted to, this is where to detect integer ABS
9178
9179 return Changed ? &SI : 0;
9180}
9181
Chris Lattner3d69f462004-03-12 05:52:32 +00009182Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009183 Value *CondVal = SI.getCondition();
9184 Value *TrueVal = SI.getTrueValue();
9185 Value *FalseVal = SI.getFalseValue();
9186
9187 // select true, X, Y -> X
9188 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009189 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009190 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009191
9192 // select C, X, X -> X
9193 if (TrueVal == FalseVal)
9194 return ReplaceInstUsesWith(SI, TrueVal);
9195
Chris Lattnere87597f2004-10-16 18:11:37 +00009196 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9197 return ReplaceInstUsesWith(SI, FalseVal);
9198 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9199 return ReplaceInstUsesWith(SI, TrueVal);
9200 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9201 if (isa<Constant>(TrueVal))
9202 return ReplaceInstUsesWith(SI, TrueVal);
9203 else
9204 return ReplaceInstUsesWith(SI, FalseVal);
9205 }
9206
Owen Anderson1d0be152009-08-13 21:58:54 +00009207 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009208 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009209 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009210 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009211 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009212 } else {
9213 // Change: A = select B, false, C --> A = and !B, C
9214 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009215 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009216 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009217 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009218 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009219 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009220 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009221 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009222 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009223 } else {
9224 // Change: A = select B, C, true --> A = or !B, C
9225 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009226 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009227 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009228 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009229 }
9230 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009231
9232 // select a, b, a -> a&b
9233 // select a, a, b -> a|b
9234 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009235 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009236 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009237 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009238 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009239
Chris Lattner2eefe512004-04-09 19:05:30 +00009240 // Selecting between two integer constants?
9241 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9242 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009243 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009244 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009245 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009246 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009247 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009248 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009249 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009250 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009251 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009252 }
Chris Lattner457dd822004-06-09 07:59:58 +00009253
Reid Spencere4d87aa2006-12-23 06:05:41 +00009254 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009255 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009256 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009257 // non-constant value, eliminate this whole mess. This corresponds to
9258 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009259 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009260 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009261 cast<Constant>(IC->getOperand(1))->isNullValue())
9262 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9263 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009264 isa<ConstantInt>(ICA->getOperand(1)) &&
9265 (ICA->getOperand(1) == TrueValC ||
9266 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009267 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9268 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009269 // know whether we have a icmp_ne or icmp_eq and whether the
9270 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009271 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009272 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009273 Value *V = ICA;
9274 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009275 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009276 Instruction::Xor, V, ICA->getOperand(1)), SI);
9277 return ReplaceInstUsesWith(SI, V);
9278 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009279 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009280 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009281
9282 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009283 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9284 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009285 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009286 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9287 // This is not safe in general for floating point:
9288 // consider X== -0, Y== +0.
9289 // It becomes safe if either operand is a nonzero constant.
9290 ConstantFP *CFPt, *CFPf;
9291 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9292 !CFPt->getValueAPF().isZero()) ||
9293 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9294 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009295 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009296 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009297 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009298 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009299 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009300 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009301
Reid Spencere4d87aa2006-12-23 06:05:41 +00009302 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009303 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009304 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9305 // This is not safe in general for floating point:
9306 // consider X== -0, Y== +0.
9307 // It becomes safe if either operand is a nonzero constant.
9308 ConstantFP *CFPt, *CFPf;
9309 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9310 !CFPt->getValueAPF().isZero()) ||
9311 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9312 !CFPf->getValueAPF().isZero()))
9313 return ReplaceInstUsesWith(SI, FalseVal);
9314 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009315 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009316 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9317 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009318 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009319 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009320 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009321 }
9322
9323 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009324 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9325 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9326 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009327
Chris Lattner87875da2005-01-13 22:52:24 +00009328 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9329 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9330 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009331 Instruction *AddOp = 0, *SubOp = 0;
9332
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009333 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9334 if (TI->getOpcode() == FI->getOpcode())
9335 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9336 return IV;
9337
9338 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9339 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009340 if ((TI->getOpcode() == Instruction::Sub &&
9341 FI->getOpcode() == Instruction::Add) ||
9342 (TI->getOpcode() == Instruction::FSub &&
9343 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009344 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009345 } else if ((FI->getOpcode() == Instruction::Sub &&
9346 TI->getOpcode() == Instruction::Add) ||
9347 (FI->getOpcode() == Instruction::FSub &&
9348 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009349 AddOp = TI; SubOp = FI;
9350 }
9351
9352 if (AddOp) {
9353 Value *OtherAddOp = 0;
9354 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9355 OtherAddOp = AddOp->getOperand(1);
9356 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9357 OtherAddOp = AddOp->getOperand(0);
9358 }
9359
9360 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009361 // So at this point we know we have (Y -> OtherAddOp):
9362 // select C, (add X, Y), (sub X, Z)
9363 Value *NegVal; // Compute -Z
9364 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009365 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009366 } else {
9367 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009368 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009369 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009370 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009371
9372 Value *NewTrueOp = OtherAddOp;
9373 Value *NewFalseOp = NegVal;
9374 if (AddOp != TI)
9375 std::swap(NewTrueOp, NewFalseOp);
9376 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009377 SelectInst::Create(CondVal, NewTrueOp,
9378 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009379
9380 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009381 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009382 }
9383 }
9384 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009385
Chris Lattnere576b912004-04-09 23:46:01 +00009386 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009387 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009388 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9389 if (FoldI)
9390 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009391 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009392
9393 if (BinaryOperator::isNot(CondVal)) {
9394 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9395 SI.setOperand(1, FalseVal);
9396 SI.setOperand(2, TrueVal);
9397 return &SI;
9398 }
9399
Chris Lattner3d69f462004-03-12 05:52:32 +00009400 return 0;
9401}
9402
Dan Gohmaneee962e2008-04-10 18:43:06 +00009403/// EnforceKnownAlignment - If the specified pointer points to an object that
9404/// we control, modify the object's alignment to PrefAlign. This isn't
9405/// often possible though. If alignment is important, a more reliable approach
9406/// is to simply align all global variables and allocation instructions to
9407/// their preferred alignment from the beginning.
9408///
9409static unsigned EnforceKnownAlignment(Value *V,
9410 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009411
Dan Gohmaneee962e2008-04-10 18:43:06 +00009412 User *U = dyn_cast<User>(V);
9413 if (!U) return Align;
9414
Dan Gohmanca178902009-07-17 20:47:02 +00009415 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009416 default: break;
9417 case Instruction::BitCast:
9418 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9419 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009420 // If all indexes are zero, it is just the alignment of the base pointer.
9421 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009422 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009423 if (!isa<Constant>(*i) ||
9424 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009425 AllZeroOperands = false;
9426 break;
9427 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009428
9429 if (AllZeroOperands) {
9430 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009431 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009432 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009433 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009434 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009435 }
9436
9437 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9438 // If there is a large requested alignment and we can, bump up the alignment
9439 // of the global.
9440 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009441 if (GV->getAlignment() >= PrefAlign)
9442 Align = GV->getAlignment();
9443 else {
9444 GV->setAlignment(PrefAlign);
9445 Align = PrefAlign;
9446 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009447 }
9448 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9449 // If there is a requested alignment and if this is an alloca, round up. We
9450 // don't do this for malloc, because some systems can't respect the request.
9451 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009452 if (AI->getAlignment() >= PrefAlign)
9453 Align = AI->getAlignment();
9454 else {
9455 AI->setAlignment(PrefAlign);
9456 Align = PrefAlign;
9457 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009458 }
9459 }
9460
9461 return Align;
9462}
9463
9464/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9465/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9466/// and it is more than the alignment of the ultimate object, see if we can
9467/// increase the alignment of the ultimate object, making this check succeed.
9468unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9469 unsigned PrefAlign) {
9470 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9471 sizeof(PrefAlign) * CHAR_BIT;
9472 APInt Mask = APInt::getAllOnesValue(BitWidth);
9473 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9474 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9475 unsigned TrailZ = KnownZero.countTrailingOnes();
9476 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9477
9478 if (PrefAlign > Align)
9479 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9480
9481 // We don't need to make any adjustment.
9482 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009483}
9484
Chris Lattnerf497b022008-01-13 23:50:23 +00009485Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009486 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009487 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009488 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009489 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009490
9491 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009492 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009493 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009494 return MI;
9495 }
9496
9497 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9498 // load/store.
9499 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9500 if (MemOpLength == 0) return 0;
9501
Chris Lattner37ac6082008-01-14 00:28:35 +00009502 // Source and destination pointer types are always "i8*" for intrinsic. See
9503 // if the size is something we can handle with a single primitive load/store.
9504 // A single load+store correctly handles overlapping memory in the memmove
9505 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009506 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009507 if (Size == 0) return MI; // Delete this mem transfer.
9508
9509 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009510 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009511
Chris Lattner37ac6082008-01-14 00:28:35 +00009512 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009513 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009514 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009515
9516 // Memcpy forces the use of i8* for the source and destination. That means
9517 // that if you're using memcpy to move one double around, you'll get a cast
9518 // from double* to i8*. We'd much rather use a double load+store rather than
9519 // an i64 load+store, here because this improves the odds that the source or
9520 // dest address will be promotable. See if we can find a better type than the
9521 // integer datatype.
9522 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9523 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009524 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009525 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9526 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009527 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009528 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9529 if (STy->getNumElements() == 1)
9530 SrcETy = STy->getElementType(0);
9531 else
9532 break;
9533 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9534 if (ATy->getNumElements() == 1)
9535 SrcETy = ATy->getElementType();
9536 else
9537 break;
9538 } else
9539 break;
9540 }
9541
Dan Gohman8f8e2692008-05-23 01:52:21 +00009542 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009543 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009544 }
9545 }
9546
9547
Chris Lattnerf497b022008-01-13 23:50:23 +00009548 // If the memcpy/memmove provides better alignment info than we can
9549 // infer, use it.
9550 SrcAlign = std::max(SrcAlign, CopyAlign);
9551 DstAlign = std::max(DstAlign, CopyAlign);
9552
Chris Lattner08142f22009-08-30 19:47:22 +00009553 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9554 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009555 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9556 InsertNewInstBefore(L, *MI);
9557 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9558
9559 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009560 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009561 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009562}
Chris Lattner3d69f462004-03-12 05:52:32 +00009563
Chris Lattner69ea9d22008-04-30 06:39:11 +00009564Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9565 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009566 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009567 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009568 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009569 return MI;
9570 }
9571
9572 // Extract the length and alignment and fill if they are constant.
9573 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9574 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009575 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009576 return 0;
9577 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009578 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009579
9580 // If the length is zero, this is a no-op
9581 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9582
9583 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9584 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009585 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009586
9587 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +00009588 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009589
9590 // Alignment 0 is identity for alignment 1 for memset, but not store.
9591 if (Alignment == 0) Alignment = 1;
9592
9593 // Extract the fill value and store.
9594 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009595 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009596 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009597
9598 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009599 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009600 return MI;
9601 }
9602
9603 return 0;
9604}
9605
9606
Chris Lattner8b0ea312006-01-13 20:11:04 +00009607/// visitCallInst - CallInst simplification. This mostly only handles folding
9608/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9609/// the heavy lifting.
9610///
Chris Lattner9fe38862003-06-19 17:00:31 +00009611Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009612 // If the caller function is nounwind, mark the call as nounwind, even if the
9613 // callee isn't.
9614 if (CI.getParent()->getParent()->doesNotThrow() &&
9615 !CI.doesNotThrow()) {
9616 CI.setDoesNotThrow();
9617 return &CI;
9618 }
9619
Chris Lattner8b0ea312006-01-13 20:11:04 +00009620 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9621 if (!II) return visitCallSite(&CI);
9622
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009623 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9624 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009625 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009626 bool Changed = false;
9627
9628 // memmove/cpy/set of zero bytes is a noop.
9629 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9630 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9631
Chris Lattner35b9e482004-10-12 04:52:52 +00009632 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009633 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009634 // Replace the instruction with just byte operations. We would
9635 // transform other cases to loads/stores, but we don't know if
9636 // alignment is sufficient.
9637 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009638 }
9639
Chris Lattner35b9e482004-10-12 04:52:52 +00009640 // If we have a memmove and the source operation is a constant global,
9641 // then the source and dest pointers can't alias, so we can change this
9642 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009643 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009644 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9645 if (GVSrc->isConstant()) {
9646 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009647 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9648 const Type *Tys[1];
9649 Tys[0] = CI.getOperand(3)->getType();
9650 CI.setOperand(0,
9651 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009652 Changed = true;
9653 }
Chris Lattnera935db82008-05-28 05:30:41 +00009654
9655 // memmove(x,x,size) -> noop.
9656 if (MMI->getSource() == MMI->getDest())
9657 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009658 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009659
Chris Lattner95a959d2006-03-06 20:18:44 +00009660 // If we can determine a pointer alignment that is bigger than currently
9661 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009662 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009663 if (Instruction *I = SimplifyMemTransfer(MI))
9664 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009665 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9666 if (Instruction *I = SimplifyMemSet(MSI))
9667 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009668 }
9669
Chris Lattner8b0ea312006-01-13 20:11:04 +00009670 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009671 }
9672
9673 switch (II->getIntrinsicID()) {
9674 default: break;
9675 case Intrinsic::bswap:
9676 // bswap(bswap(x)) -> x
9677 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9678 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9679 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9680 break;
9681 case Intrinsic::ppc_altivec_lvx:
9682 case Intrinsic::ppc_altivec_lvxl:
9683 case Intrinsic::x86_sse_loadu_ps:
9684 case Intrinsic::x86_sse2_loadu_pd:
9685 case Intrinsic::x86_sse2_loadu_dq:
9686 // Turn PPC lvx -> load if the pointer is known aligned.
9687 // Turn X86 loadups -> load if the pointer is known aligned.
9688 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +00009689 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9690 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +00009691 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009692 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009693 break;
9694 case Intrinsic::ppc_altivec_stvx:
9695 case Intrinsic::ppc_altivec_stvxl:
9696 // Turn stvx -> store if the pointer is known aligned.
9697 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9698 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009699 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009700 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009701 return new StoreInst(II->getOperand(1), Ptr);
9702 }
9703 break;
9704 case Intrinsic::x86_sse_storeu_ps:
9705 case Intrinsic::x86_sse2_storeu_pd:
9706 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009707 // Turn X86 storeu -> store if the pointer is known aligned.
9708 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9709 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009710 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +00009711 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +00009712 return new StoreInst(II->getOperand(2), Ptr);
9713 }
9714 break;
9715
9716 case Intrinsic::x86_sse_cvttss2si: {
9717 // These intrinsics only demands the 0th element of its input vector. If
9718 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009719 unsigned VWidth =
9720 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9721 APInt DemandedElts(VWidth, 1);
9722 APInt UndefElts(VWidth, 0);
9723 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009724 UndefElts)) {
9725 II->setOperand(1, V);
9726 return II;
9727 }
9728 break;
9729 }
9730
9731 case Intrinsic::ppc_altivec_vperm:
9732 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9733 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9734 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009735
Chris Lattner0521e3c2008-06-18 04:33:20 +00009736 // Check that all of the elements are integer constants or undefs.
9737 bool AllEltsOk = true;
9738 for (unsigned i = 0; i != 16; ++i) {
9739 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9740 !isa<UndefValue>(Mask->getOperand(i))) {
9741 AllEltsOk = false;
9742 break;
9743 }
9744 }
9745
9746 if (AllEltsOk) {
9747 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +00009748 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9749 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009750 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009751
Chris Lattner0521e3c2008-06-18 04:33:20 +00009752 // Only extract each element once.
9753 Value *ExtractedElts[32];
9754 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9755
Chris Lattnere2ed0572006-04-06 19:19:17 +00009756 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009757 if (isa<UndefValue>(Mask->getOperand(i)))
9758 continue;
9759 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9760 Idx &= 31; // Match the hardware behavior.
9761
9762 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009763 ExtractedElts[Idx] =
9764 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9765 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9766 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009767 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009768
Chris Lattner0521e3c2008-06-18 04:33:20 +00009769 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009770 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9771 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9772 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009773 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009774 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009775 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009776 }
9777 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009778
Chris Lattner0521e3c2008-06-18 04:33:20 +00009779 case Intrinsic::stackrestore: {
9780 // If the save is right next to the restore, remove the restore. This can
9781 // happen when variable allocas are DCE'd.
9782 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9783 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9784 BasicBlock::iterator BI = SS;
9785 if (&*++BI == II)
9786 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009787 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009788 }
9789
9790 // Scan down this block to see if there is another stack restore in the
9791 // same block without an intervening call/alloca.
9792 BasicBlock::iterator BI = II;
9793 TerminatorInst *TI = II->getParent()->getTerminator();
9794 bool CannotRemove = false;
9795 for (++BI; &*BI != TI; ++BI) {
9796 if (isa<AllocaInst>(BI)) {
9797 CannotRemove = true;
9798 break;
9799 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009800 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9801 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9802 // If there is a stackrestore below this one, remove this one.
9803 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9804 return EraseInstFromFunction(CI);
9805 // Otherwise, ignore the intrinsic.
9806 } else {
9807 // If we found a non-intrinsic call, we can't remove the stack
9808 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009809 CannotRemove = true;
9810 break;
9811 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009812 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009813 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009814
9815 // If the stack restore is in a return/unwind block and if there are no
9816 // allocas or calls between the restore and the return, nuke the restore.
9817 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9818 return EraseInstFromFunction(CI);
9819 break;
9820 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009821 }
9822
Chris Lattner8b0ea312006-01-13 20:11:04 +00009823 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009824}
9825
9826// InvokeInst simplification
9827//
9828Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009829 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009830}
9831
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009832/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9833/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009834static bool isSafeToEliminateVarargsCast(const CallSite CS,
9835 const CastInst * const CI,
9836 const TargetData * const TD,
9837 const int ix) {
9838 if (!CI->isLosslessCast())
9839 return false;
9840
9841 // The size of ByVal arguments is derived from the type, so we
9842 // can't change to a type with a different size. If the size were
9843 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009844 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009845 return true;
9846
9847 const Type* SrcTy =
9848 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9849 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9850 if (!SrcTy->isSized() || !DstTy->isSized())
9851 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009852 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009853 return false;
9854 return true;
9855}
9856
Chris Lattnera44d8a22003-10-07 22:32:43 +00009857// visitCallSite - Improvements for call and invoke instructions.
9858//
9859Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009860 bool Changed = false;
9861
9862 // If the callee is a constexpr cast of a function, attempt to move the cast
9863 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009864 if (transformConstExprCastCall(CS)) return 0;
9865
Chris Lattner6c266db2003-10-07 22:54:13 +00009866 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009867
Chris Lattner08b22ec2005-05-13 07:09:09 +00009868 if (Function *CalleeF = dyn_cast<Function>(Callee))
9869 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9870 Instruction *OldCall = CS.getInstruction();
9871 // If the call and callee calling conventions don't match, this call must
9872 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009873 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009874 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009875 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009876 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009877 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009878 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9879 return EraseInstFromFunction(*OldCall);
9880 return 0;
9881 }
9882
Chris Lattner17be6352004-10-18 02:59:09 +00009883 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9884 // This instruction is not reachable, just remove it. We insert a store to
9885 // undef so that we know that this code is not reachable, despite the fact
9886 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009887 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009888 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009889 CS.getInstruction());
9890
9891 if (!CS.getInstruction()->use_empty())
9892 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009893 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009894
9895 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9896 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009897 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009898 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009899 }
Chris Lattner17be6352004-10-18 02:59:09 +00009900 return EraseInstFromFunction(*CS.getInstruction());
9901 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009902
Duncan Sandscdb6d922007-09-17 10:26:40 +00009903 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9904 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9905 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9906 return transformCallThroughTrampoline(CS);
9907
Chris Lattner6c266db2003-10-07 22:54:13 +00009908 const PointerType *PTy = cast<PointerType>(Callee->getType());
9909 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9910 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009911 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009912 // See if we can optimize any arguments passed through the varargs area of
9913 // the call.
9914 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009915 E = CS.arg_end(); I != E; ++I, ++ix) {
9916 CastInst *CI = dyn_cast<CastInst>(*I);
9917 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9918 *I = CI->getOperand(0);
9919 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009920 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009921 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009922 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009923
Duncan Sandsf0c33542007-12-19 21:13:37 +00009924 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009925 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009926 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009927 Changed = true;
9928 }
9929
Chris Lattner6c266db2003-10-07 22:54:13 +00009930 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009931}
9932
Chris Lattner9fe38862003-06-19 17:00:31 +00009933// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9934// attempt to move the cast to the arguments of the call/invoke.
9935//
9936bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9937 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9938 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009939 if (CE->getOpcode() != Instruction::BitCast ||
9940 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009941 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009942 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009943 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009944 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009945
9946 // Okay, this is a cast from a function to a different type. Unless doing so
9947 // would cause a type conversion of one of our arguments, change this call to
9948 // be a direct call with arguments casted to the appropriate types.
9949 //
9950 const FunctionType *FT = Callee->getFunctionType();
9951 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009952 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009953
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009954 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009955 return false; // TODO: Handle multiple return values.
9956
Chris Lattnerf78616b2004-01-14 06:06:08 +00009957 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009958 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009959 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009960 // Conversion is ok if changing from one pointer type to another or from
9961 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009962 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009963 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009964 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009965 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +00009966 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00009967
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009968 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009969 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +00009970 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00009971 return false; // Cannot transform this return value.
9972
Chris Lattner58d74912008-03-12 17:45:29 +00009973 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +00009974 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +00009975 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +00009976 return false; // Attribute not compatible with transformed value.
9977 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00009978
Chris Lattnerf78616b2004-01-14 06:06:08 +00009979 // If the callsite is an invoke instruction, and the return value is used by
9980 // a PHI node in a successor, we cannot change the return type of the call
9981 // because there is no place to put the cast instruction (without breaking
9982 // the critical edge). Bail out in this case.
9983 if (!Caller->use_empty())
9984 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9985 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9986 UI != E; ++UI)
9987 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9988 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00009989 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00009990 return false;
9991 }
Chris Lattner9fe38862003-06-19 17:00:31 +00009992
9993 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9994 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00009995
Chris Lattner9fe38862003-06-19 17:00:31 +00009996 CallSite::arg_iterator AI = CS.arg_begin();
9997 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9998 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00009999 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010000
10001 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010002 return false; // Cannot transform this parameter value.
10003
Devang Patel19c87462008-09-26 22:53:05 +000010004 if (CallerPAL.getParamAttributes(i + 1)
10005 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010006 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010007
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010008 // Converting from one pointer type to another or between a pointer and an
10009 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010010 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010011 (TD && ((isa<PointerType>(ParamTy) ||
10012 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10013 (isa<PointerType>(ActTy) ||
10014 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010015 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010016 }
10017
10018 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010019 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010020 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010021
Chris Lattner58d74912008-03-12 17:45:29 +000010022 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10023 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010024 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010025 // won't be dropping them. Check that these extra arguments have attributes
10026 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010027 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10028 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010029 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010030 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010031 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010032 return false;
10033 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010034
Chris Lattner9fe38862003-06-19 17:00:31 +000010035 // Okay, we decided that this is a safe thing to do: go ahead and start
10036 // inserting cast instructions as necessary...
10037 std::vector<Value*> Args;
10038 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010039 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010040 attrVec.reserve(NumCommonArgs);
10041
10042 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010043 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010044
10045 // If the return value is not being used, the type may not be compatible
10046 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010047 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010048
10049 // Add the new return attributes.
10050 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010051 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010052
10053 AI = CS.arg_begin();
10054 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10055 const Type *ParamTy = FT->getParamType(i);
10056 if ((*AI)->getType() == ParamTy) {
10057 Args.push_back(*AI);
10058 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010059 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010060 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010061 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010062 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010063
10064 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010065 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010066 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010067 }
10068
10069 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010070 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010071 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010072 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010073
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010074 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010075 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010076 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010077 errs() << "WARNING: While resolving call to function '"
10078 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010079 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010080 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010081 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10082 const Type *PTy = getPromotedType((*AI)->getType());
10083 if (PTy != (*AI)->getType()) {
10084 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010085 Instruction::CastOps opcode =
10086 CastInst::getCastOpcode(*AI, false, PTy, false);
10087 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010088 } else {
10089 Args.push_back(*AI);
10090 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010091
Duncan Sandse1e520f2008-01-13 08:02:44 +000010092 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010093 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010094 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010095 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010096 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010097 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010098
Devang Patel19c87462008-09-26 22:53:05 +000010099 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10100 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10101
Owen Anderson1d0be152009-08-13 21:58:54 +000010102 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010103 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010104
Eric Christophera66297a2009-07-25 02:45:27 +000010105 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10106 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010107
Chris Lattner9fe38862003-06-19 17:00:31 +000010108 Instruction *NC;
10109 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010110 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010111 Args.begin(), Args.end(),
10112 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010113 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010114 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010115 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010116 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10117 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010118 CallInst *CI = cast<CallInst>(Caller);
10119 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010120 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010121 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010122 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010123 }
10124
Chris Lattner6934a042007-02-11 01:23:03 +000010125 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010126 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010127 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010128 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010129 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010130 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010131 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010132
10133 // If this is an invoke instruction, we should insert it after the first
10134 // non-phi, instruction in the normal successor block.
10135 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010136 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010137 InsertNewInstBefore(NC, *I);
10138 } else {
10139 // Otherwise, it's a call, just insert cast right after the call instr
10140 InsertNewInstBefore(NC, *Caller);
10141 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010142 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010144 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010145 }
10146 }
10147
Owen Anderson1d0be152009-08-13 21:58:54 +000010148 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010149 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010150 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010151 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010152 return true;
10153}
10154
Duncan Sandscdb6d922007-09-17 10:26:40 +000010155// transformCallThroughTrampoline - Turn a call to a function created by the
10156// init_trampoline intrinsic into a direct call to the underlying function.
10157//
10158Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10159 Value *Callee = CS.getCalledValue();
10160 const PointerType *PTy = cast<PointerType>(Callee->getType());
10161 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010162 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010163
10164 // If the call already has the 'nest' attribute somewhere then give up -
10165 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010166 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010167 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010168
10169 IntrinsicInst *Tramp =
10170 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10171
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010172 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010173 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10174 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10175
Devang Patel05988662008-09-25 21:00:45 +000010176 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010177 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010178 unsigned NestIdx = 1;
10179 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010180 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010181
10182 // Look for a parameter marked with the 'nest' attribute.
10183 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10184 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010185 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010186 // Record the parameter type and any other attributes.
10187 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010188 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010189 break;
10190 }
10191
10192 if (NestTy) {
10193 Instruction *Caller = CS.getInstruction();
10194 std::vector<Value*> NewArgs;
10195 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10196
Devang Patel05988662008-09-25 21:00:45 +000010197 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010198 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010199
Duncan Sandscdb6d922007-09-17 10:26:40 +000010200 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010201 // mean appending it. Likewise for attributes.
10202
Devang Patel19c87462008-09-26 22:53:05 +000010203 // Add any result attributes.
10204 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010205 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010206
Duncan Sandscdb6d922007-09-17 10:26:40 +000010207 {
10208 unsigned Idx = 1;
10209 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10210 do {
10211 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010212 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010213 Value *NestVal = Tramp->getOperand(3);
10214 if (NestVal->getType() != NestTy)
10215 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10216 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010217 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010218 }
10219
10220 if (I == E)
10221 break;
10222
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010223 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010224 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010225 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010226 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010227 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010228
10229 ++Idx, ++I;
10230 } while (1);
10231 }
10232
Devang Patel19c87462008-09-26 22:53:05 +000010233 // Add any function attributes.
10234 if (Attributes Attr = Attrs.getFnAttributes())
10235 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10236
Duncan Sandscdb6d922007-09-17 10:26:40 +000010237 // The trampoline may have been bitcast to a bogus type (FTy).
10238 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010239 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010240
Duncan Sandscdb6d922007-09-17 10:26:40 +000010241 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010242 NewTypes.reserve(FTy->getNumParams()+1);
10243
Duncan Sandscdb6d922007-09-17 10:26:40 +000010244 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010245 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010246 {
10247 unsigned Idx = 1;
10248 FunctionType::param_iterator I = FTy->param_begin(),
10249 E = FTy->param_end();
10250
10251 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010252 if (Idx == NestIdx)
10253 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010254 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010255
10256 if (I == E)
10257 break;
10258
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010259 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010260 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010261
10262 ++Idx, ++I;
10263 } while (1);
10264 }
10265
10266 // Replace the trampoline call with a direct call. Let the generic
10267 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010268 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010269 FTy->isVarArg());
10270 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010271 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010272 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010273 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010274 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10275 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010276
10277 Instruction *NewCaller;
10278 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010279 NewCaller = InvokeInst::Create(NewCallee,
10280 II->getNormalDest(), II->getUnwindDest(),
10281 NewArgs.begin(), NewArgs.end(),
10282 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010283 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010284 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010285 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010286 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10287 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010288 if (cast<CallInst>(Caller)->isTailCall())
10289 cast<CallInst>(NewCaller)->setTailCall();
10290 cast<CallInst>(NewCaller)->
10291 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010292 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010293 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010294 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010295 Caller->replaceAllUsesWith(NewCaller);
10296 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010297 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010298 return 0;
10299 }
10300 }
10301
10302 // Replace the trampoline call with a direct call. Since there is no 'nest'
10303 // parameter, there is no need to adjust the argument list. Let the generic
10304 // code sort out any function type mismatches.
10305 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010306 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010307 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010308 CS.setCalledFunction(NewCallee);
10309 return CS.getInstruction();
10310}
10311
Chris Lattner7da52b22006-11-01 04:51:18 +000010312/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10313/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10314/// and a single binop.
10315Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10316 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010317 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010318 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010319 Value *LHSVal = FirstInst->getOperand(0);
10320 Value *RHSVal = FirstInst->getOperand(1);
10321
10322 const Type *LHSType = LHSVal->getType();
10323 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010324
10325 // Scan to see if all operands are the same opcode, all have one use, and all
10326 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010327 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010328 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010329 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010330 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010331 // types or GEP's with different index types.
10332 I->getOperand(0)->getType() != LHSType ||
10333 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010334 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010335
10336 // If they are CmpInst instructions, check their predicates
10337 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10338 if (cast<CmpInst>(I)->getPredicate() !=
10339 cast<CmpInst>(FirstInst)->getPredicate())
10340 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010341
10342 // Keep track of which operand needs a phi node.
10343 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10344 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010345 }
10346
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010347 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010348
Chris Lattner7da52b22006-11-01 04:51:18 +000010349 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010350 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010351 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010352 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010353 NewLHS = PHINode::Create(LHSType,
10354 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010355 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10356 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010357 InsertNewInstBefore(NewLHS, PN);
10358 LHSVal = NewLHS;
10359 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010360
10361 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010362 NewRHS = PHINode::Create(RHSType,
10363 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010364 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10365 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010366 InsertNewInstBefore(NewRHS, PN);
10367 RHSVal = NewRHS;
10368 }
10369
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010370 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010371 if (NewLHS || NewRHS) {
10372 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10373 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10374 if (NewLHS) {
10375 Value *NewInLHS = InInst->getOperand(0);
10376 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10377 }
10378 if (NewRHS) {
10379 Value *NewInRHS = InInst->getOperand(1);
10380 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10381 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010382 }
10383 }
10384
Chris Lattner7da52b22006-11-01 04:51:18 +000010385 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010386 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010387 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010388 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010389 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010390}
10391
Chris Lattner05f18922008-12-01 02:34:36 +000010392Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10393 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10394
10395 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10396 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010397 // This is true if all GEP bases are allocas and if all indices into them are
10398 // constants.
10399 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010400
10401 // Scan to see if all operands are the same opcode, all have one use, and all
10402 // kill their operands (i.e. the operands have one use).
10403 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10404 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10405 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10406 GEP->getNumOperands() != FirstInst->getNumOperands())
10407 return 0;
10408
Chris Lattner36d3e322009-02-21 00:46:50 +000010409 // Keep track of whether or not all GEPs are of alloca pointers.
10410 if (AllBasePointersAreAllocas &&
10411 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10412 !GEP->hasAllConstantIndices()))
10413 AllBasePointersAreAllocas = false;
10414
Chris Lattner05f18922008-12-01 02:34:36 +000010415 // Compare the operand lists.
10416 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10417 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10418 continue;
10419
10420 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10421 // if one of the PHIs has a constant for the index. The index may be
10422 // substantially cheaper to compute for the constants, so making it a
10423 // variable index could pessimize the path. This also handles the case
10424 // for struct indices, which must always be constant.
10425 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10426 isa<ConstantInt>(GEP->getOperand(op)))
10427 return 0;
10428
10429 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10430 return 0;
10431 FixedOperands[op] = 0; // Needs a PHI.
10432 }
10433 }
10434
Chris Lattner36d3e322009-02-21 00:46:50 +000010435 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010436 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010437 // offset calculation, but all the predecessors will have to materialize the
10438 // stack address into a register anyway. We'd actually rather *clone* the
10439 // load up into the predecessors so that we have a load of a gep of an alloca,
10440 // which can usually all be folded into the load.
10441 if (AllBasePointersAreAllocas)
10442 return 0;
10443
Chris Lattner05f18922008-12-01 02:34:36 +000010444 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10445 // that is variable.
10446 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10447
10448 bool HasAnyPHIs = false;
10449 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10450 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10451 Value *FirstOp = FirstInst->getOperand(i);
10452 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10453 FirstOp->getName()+".pn");
10454 InsertNewInstBefore(NewPN, PN);
10455
10456 NewPN->reserveOperandSpace(e);
10457 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10458 OperandPhis[i] = NewPN;
10459 FixedOperands[i] = NewPN;
10460 HasAnyPHIs = true;
10461 }
10462
10463
10464 // Add all operands to the new PHIs.
10465 if (HasAnyPHIs) {
10466 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10467 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10468 BasicBlock *InBB = PN.getIncomingBlock(i);
10469
10470 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10471 if (PHINode *OpPhi = OperandPhis[op])
10472 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10473 }
10474 }
10475
10476 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010477 GetElementPtrInst *GEP =
10478 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10479 FixedOperands.end());
10480 if (cast<GEPOperator>(FirstInst)->isInBounds())
10481 cast<GEPOperator>(GEP)->setIsInBounds(true);
10482 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010483}
10484
10485
Chris Lattner21550882009-02-23 05:56:17 +000010486/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10487/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010488/// obvious the value of the load is not changed from the point of the load to
10489/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010490///
10491/// Finally, it is safe, but not profitable, to sink a load targetting a
10492/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10493/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010494static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010495 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10496
10497 for (++BBI; BBI != E; ++BBI)
10498 if (BBI->mayWriteToMemory())
10499 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010500
10501 // Check for non-address taken alloca. If not address-taken already, it isn't
10502 // profitable to do this xform.
10503 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10504 bool isAddressTaken = false;
10505 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10506 UI != E; ++UI) {
10507 if (isa<LoadInst>(UI)) continue;
10508 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10509 // If storing TO the alloca, then the address isn't taken.
10510 if (SI->getOperand(1) == AI) continue;
10511 }
10512 isAddressTaken = true;
10513 break;
10514 }
10515
Chris Lattner36d3e322009-02-21 00:46:50 +000010516 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010517 return false;
10518 }
10519
Chris Lattner36d3e322009-02-21 00:46:50 +000010520 // If this load is a load from a GEP with a constant offset from an alloca,
10521 // then we don't want to sink it. In its present form, it will be
10522 // load [constant stack offset]. Sinking it will cause us to have to
10523 // materialize the stack addresses in each predecessor in a register only to
10524 // do a shared load from register in the successor.
10525 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10526 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10527 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10528 return false;
10529
Chris Lattner76c73142006-11-01 07:13:54 +000010530 return true;
10531}
10532
Chris Lattner9fe38862003-06-19 17:00:31 +000010533
Chris Lattnerbac32862004-11-14 19:13:23 +000010534// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10535// operator and they all are only used by the PHI, PHI together their
10536// inputs, and do the operation once, to the result of the PHI.
10537Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10538 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10539
10540 // Scan the instruction, looking for input operations that can be folded away.
10541 // If all input operands to the phi are the same instruction (e.g. a cast from
10542 // the same type or "+42") we can pull the operation through the PHI, reducing
10543 // code size and simplifying code.
10544 Constant *ConstantOp = 0;
10545 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010546 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010547 if (isa<CastInst>(FirstInst)) {
10548 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010549 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010550 // Can fold binop, compare or shift here if the RHS is a constant,
10551 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010552 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010553 if (ConstantOp == 0)
10554 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010555 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10556 isVolatile = LI->isVolatile();
10557 // We can't sink the load if the loaded value could be modified between the
10558 // load and the PHI.
10559 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010560 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010561 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010562
10563 // If the PHI is of volatile loads and the load block has multiple
10564 // successors, sinking it would remove a load of the volatile value from
10565 // the path through the other successor.
10566 if (isVolatile &&
10567 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10568 return 0;
10569
Chris Lattner9c080502006-11-01 07:43:41 +000010570 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010571 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010572 } else {
10573 return 0; // Cannot fold this operation.
10574 }
10575
10576 // Check to see if all arguments are the same operation.
10577 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10578 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10579 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010580 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010581 return 0;
10582 if (CastSrcTy) {
10583 if (I->getOperand(0)->getType() != CastSrcTy)
10584 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010585 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010586 // We can't sink the load if the loaded value could be modified between
10587 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010588 if (LI->isVolatile() != isVolatile ||
10589 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010590 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010591 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010592
Chris Lattner71042962008-07-08 17:18:32 +000010593 // If the PHI is of volatile loads and the load block has multiple
10594 // successors, sinking it would remove a load of the volatile value from
10595 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010596 if (isVolatile &&
10597 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10598 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010599
Chris Lattnerbac32862004-11-14 19:13:23 +000010600 } else if (I->getOperand(1) != ConstantOp) {
10601 return 0;
10602 }
10603 }
10604
10605 // Okay, they are all the same operation. Create a new PHI node of the
10606 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010607 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10608 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010609 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010610
10611 Value *InVal = FirstInst->getOperand(0);
10612 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010613
10614 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010615 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10616 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10617 if (NewInVal != InVal)
10618 InVal = 0;
10619 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10620 }
10621
10622 Value *PhiVal;
10623 if (InVal) {
10624 // The new PHI unions all of the same values together. This is really
10625 // common, so we handle it intelligently here for compile-time speed.
10626 PhiVal = InVal;
10627 delete NewPN;
10628 } else {
10629 InsertNewInstBefore(NewPN, PN);
10630 PhiVal = NewPN;
10631 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010632
Chris Lattnerbac32862004-11-14 19:13:23 +000010633 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010634 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010635 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010636 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010637 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010638 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010639 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010640 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010641 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10642
10643 // If this was a volatile load that we are merging, make sure to loop through
10644 // and mark all the input loads as non-volatile. If we don't do this, we will
10645 // insert a new volatile load and the old ones will not be deletable.
10646 if (isVolatile)
10647 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10648 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10649
10650 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010651}
Chris Lattnera1be5662002-05-02 17:06:02 +000010652
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010653/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10654/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010655static bool DeadPHICycle(PHINode *PN,
10656 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010657 if (PN->use_empty()) return true;
10658 if (!PN->hasOneUse()) return false;
10659
10660 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010661 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010662 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010663
10664 // Don't scan crazily complex things.
10665 if (PotentiallyDeadPHIs.size() == 16)
10666 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010667
10668 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10669 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010670
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010671 return false;
10672}
10673
Chris Lattnercf5008a2007-11-06 21:52:06 +000010674/// PHIsEqualValue - Return true if this phi node is always equal to
10675/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10676/// z = some value; x = phi (y, z); y = phi (x, z)
10677static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10678 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10679 // See if we already saw this PHI node.
10680 if (!ValueEqualPHIs.insert(PN))
10681 return true;
10682
10683 // Don't scan crazily complex things.
10684 if (ValueEqualPHIs.size() == 16)
10685 return false;
10686
10687 // Scan the operands to see if they are either phi nodes or are equal to
10688 // the value.
10689 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10690 Value *Op = PN->getIncomingValue(i);
10691 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10692 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10693 return false;
10694 } else if (Op != NonPhiInVal)
10695 return false;
10696 }
10697
10698 return true;
10699}
10700
10701
Chris Lattner473945d2002-05-06 18:06:38 +000010702// PHINode simplification
10703//
Chris Lattner7e708292002-06-25 16:13:24 +000010704Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010705 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010706 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010707
Owen Anderson7e057142006-07-10 22:03:18 +000010708 if (Value *V = PN.hasConstantValue())
10709 return ReplaceInstUsesWith(PN, V);
10710
Owen Anderson7e057142006-07-10 22:03:18 +000010711 // If all PHI operands are the same operation, pull them through the PHI,
10712 // reducing code size.
10713 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010714 isa<Instruction>(PN.getIncomingValue(1)) &&
10715 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10716 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10717 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10718 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010719 PN.getIncomingValue(0)->hasOneUse())
10720 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10721 return Result;
10722
10723 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10724 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10725 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010726 if (PN.hasOneUse()) {
10727 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10728 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010729 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010730 PotentiallyDeadPHIs.insert(&PN);
10731 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010732 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010733 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010734
10735 // If this phi has a single use, and if that use just computes a value for
10736 // the next iteration of a loop, delete the phi. This occurs with unused
10737 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10738 // common case here is good because the only other things that catch this
10739 // are induction variable analysis (sometimes) and ADCE, which is only run
10740 // late.
10741 if (PHIUser->hasOneUse() &&
10742 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10743 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010744 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010745 }
10746 }
Owen Anderson7e057142006-07-10 22:03:18 +000010747
Chris Lattnercf5008a2007-11-06 21:52:06 +000010748 // We sometimes end up with phi cycles that non-obviously end up being the
10749 // same value, for example:
10750 // z = some value; x = phi (y, z); y = phi (x, z)
10751 // where the phi nodes don't necessarily need to be in the same block. Do a
10752 // quick check to see if the PHI node only contains a single non-phi value, if
10753 // so, scan to see if the phi cycle is actually equal to that value.
10754 {
10755 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10756 // Scan for the first non-phi operand.
10757 while (InValNo != NumOperandVals &&
10758 isa<PHINode>(PN.getIncomingValue(InValNo)))
10759 ++InValNo;
10760
10761 if (InValNo != NumOperandVals) {
10762 Value *NonPhiInVal = PN.getOperand(InValNo);
10763
10764 // Scan the rest of the operands to see if there are any conflicts, if so
10765 // there is no need to recursively scan other phis.
10766 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10767 Value *OpVal = PN.getIncomingValue(InValNo);
10768 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10769 break;
10770 }
10771
10772 // If we scanned over all operands, then we have one unique value plus
10773 // phi values. Scan PHI nodes to see if they all merge in each other or
10774 // the value.
10775 if (InValNo == NumOperandVals) {
10776 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10777 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10778 return ReplaceInstUsesWith(PN, NonPhiInVal);
10779 }
10780 }
10781 }
Chris Lattner60921c92003-12-19 05:58:40 +000010782 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010783}
10784
Chris Lattner7e708292002-06-25 16:13:24 +000010785Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010786 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010787 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010788 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010789 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010790 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010791
Chris Lattnere87597f2004-10-16 18:11:37 +000010792 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010793 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010794
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010795 bool HasZeroPointerIndex = false;
10796 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10797 HasZeroPointerIndex = C->isNullValue();
10798
10799 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010800 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010801
Chris Lattner28977af2004-04-05 01:30:19 +000010802 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010803 if (TD) {
10804 bool MadeChange = false;
10805 unsigned PtrSize = TD->getPointerSizeInBits();
10806
10807 gep_type_iterator GTI = gep_type_begin(GEP);
10808 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10809 I != E; ++I, ++GTI) {
10810 if (!isa<SequentialType>(*GTI)) continue;
10811
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010812 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010813 // to what we need. If narrower, sign-extend it to what we need. This
10814 // explicit cast can make subsequent optimizations more obvious.
10815 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000010816 if (OpBits == PtrSize)
10817 continue;
10818
Chris Lattner2345d1d2009-08-30 20:01:10 +000010819 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010820 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010821 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010822 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010823 }
Chris Lattner28977af2004-04-05 01:30:19 +000010824
Chris Lattner90ac28c2002-08-02 19:29:35 +000010825 // Combine Indices - If the source pointer to this getelementptr instruction
10826 // is a getelementptr instruction, combine the indices of the two
10827 // getelementptr instructions into a single instruction.
10828 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010829 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010830 // Note that if our source is a gep chain itself that we wait for that
10831 // chain to be resolved before we perform this transformation. This
10832 // avoids us creating a TON of code in some cases.
10833 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010834 if (GetElementPtrInst *SrcGEP =
10835 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10836 if (SrcGEP->getNumOperands() == 2)
10837 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010838
Chris Lattner72588fc2007-02-15 22:48:32 +000010839 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010840
10841 // Find out whether the last index in the source GEP is a sequential idx.
10842 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010843 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10844 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010845 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010846
Chris Lattner90ac28c2002-08-02 19:29:35 +000010847 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010848 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010849 // Replace: gep (gep %P, long B), long A, ...
10850 // With: T = long A+B; gep %P, T, ...
10851 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010852 Value *Sum;
10853 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10854 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010855 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010856 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010857 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010858 Sum = SO1;
10859 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010860 // If they aren't the same type, then the input hasn't been processed
10861 // by the loop above yet (which canonicalizes sequential index types to
10862 // intptr_t). Just avoid transforming this until the input has been
10863 // normalized.
10864 if (SO1->getType() != GO1->getType())
10865 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010866 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010867 }
Chris Lattner620ce142004-05-07 22:09:22 +000010868
Chris Lattnerab984842009-08-30 05:30:55 +000010869 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010870 if (Src->getNumOperands() == 2) {
10871 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010872 GEP.setOperand(1, Sum);
10873 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010874 }
Chris Lattnerab984842009-08-30 05:30:55 +000010875 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010876 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010877 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010878 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010879 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010880 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010881 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010882 Indices.append(Src->op_begin()+1, Src->op_end());
10883 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010884 }
10885
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010886 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000010887 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010888 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010889 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010890 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010891 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10892 return NewGEP;
10893 }
Chris Lattner6e24d832009-08-30 05:00:50 +000010894 }
10895
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010896 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10897 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010898 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10899
10900 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010901 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10902 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010903 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010904 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10905 // into : GEP i8* X, ...
10906 //
Chris Lattnereed48272005-09-13 00:40:14 +000010907 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010908 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10909 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010910 if (const ArrayType *CATy =
10911 dyn_cast<ArrayType>(CPTy->getElementType())) {
10912 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10913 if (CATy->getElementType() == XTy->getElementType()) {
10914 // -> GEP i8* X, ...
10915 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010916 GetElementPtrInst *NewGEP =
10917 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10918 GEP.getName());
10919 if (cast<GEPOperator>(&GEP)->isInBounds())
10920 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10921 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010922 } else if (const ArrayType *XATy =
10923 dyn_cast<ArrayType>(XTy->getElementType())) {
10924 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010925 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010926 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010927 // At this point, we know that the cast source type is a pointer
10928 // to an array of the same type as the destination pointer
10929 // array. Because the array type is never stepped over (there
10930 // is a leading zero) we can fold the cast into this GEP.
10931 GEP.setOperand(0, X);
10932 return &GEP;
10933 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010934 }
10935 }
Chris Lattnereed48272005-09-13 00:40:14 +000010936 } else if (GEP.getNumOperands() == 2) {
10937 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010938 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10939 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010940 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10941 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010942 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010943 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10944 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010945 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000010946 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000010947 Idx[1] = GEP.getOperand(1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010948 Value *NewGEP =
10949 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010950 if (cast<GEPOperator>(&GEP)->isInBounds())
10951 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000010952 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010953 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010954 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010955
10956 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010957 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010958 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010959 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010960
Owen Anderson1d0be152009-08-13 21:58:54 +000010961 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000010962 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000010963 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000010964
10965 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10966 // allow either a mul, shift, or constant here.
10967 Value *NewIdx = 0;
10968 ConstantInt *Scale = 0;
10969 if (ArrayEltSize == 1) {
10970 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000010971 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010972 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010973 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010974 Scale = CI;
10975 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10976 if (Inst->getOpcode() == Instruction::Shl &&
10977 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000010978 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10979 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000010980 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000010981 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000010982 NewIdx = Inst->getOperand(0);
10983 } else if (Inst->getOpcode() == Instruction::Mul &&
10984 isa<ConstantInt>(Inst->getOperand(1))) {
10985 Scale = cast<ConstantInt>(Inst->getOperand(1));
10986 NewIdx = Inst->getOperand(0);
10987 }
10988 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010989
Chris Lattner7835cdd2005-09-13 18:36:04 +000010990 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010991 // out, perform the transformation. Note, we don't know whether Scale is
10992 // signed or not. We'll use unsigned version of division/modulo
10993 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000010994 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010995 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010996 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010997 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000010998 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000010999 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11000 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011001 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011002 }
11003
11004 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011005 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011006 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011007 Idx[1] = NewIdx;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011008 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011009 if (cast<GEPOperator>(&GEP)->isInBounds())
11010 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011011 // The NewGEP must be pointer typed, so must the old one -> BitCast
11012 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011013 }
11014 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011015 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011016 }
Chris Lattner58407792009-01-09 04:53:57 +000011017
Chris Lattner46cd5a12009-01-09 05:44:56 +000011018 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011019 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011020 /// Y = gep X, <...constant indices...>
11021 /// into a gep of the original struct. This is important for SROA and alias
11022 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011023 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011024 if (TD &&
11025 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011026 // Determine how much the GEP moves the pointer. We are guaranteed to get
11027 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011028 ConstantInt *OffsetV =
11029 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011030 int64_t Offset = OffsetV->getSExtValue();
11031
11032 // If this GEP instruction doesn't move the pointer, just replace the GEP
11033 // with a bitcast of the real input to the dest type.
11034 if (Offset == 0) {
11035 // If the bitcast is of an allocation, and the allocation will be
11036 // converted to match the type of the cast, don't touch this.
11037 if (isa<AllocationInst>(BCI->getOperand(0))) {
11038 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11039 if (Instruction *I = visitBitCast(*BCI)) {
11040 if (I != BCI) {
11041 I->takeName(BCI);
11042 BCI->getParent()->getInstList().insert(BCI, I);
11043 ReplaceInstUsesWith(*BCI, I);
11044 }
11045 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011046 }
Chris Lattner58407792009-01-09 04:53:57 +000011047 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011048 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011049 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011050
11051 // Otherwise, if the offset is non-zero, we need to find out if there is a
11052 // field at Offset in 'A's type. If so, we can pull the cast through the
11053 // GEP.
11054 SmallVector<Value*, 8> NewIndices;
11055 const Type *InTy =
11056 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011057 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011058 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11059 NewIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011060 if (cast<GEPOperator>(&GEP)->isInBounds())
11061 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011062
11063 if (NGEP->getType() == GEP.getType())
11064 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011065 NGEP->takeName(&GEP);
11066 return new BitCastInst(NGEP, GEP.getType());
11067 }
Chris Lattner58407792009-01-09 04:53:57 +000011068 }
11069 }
11070
Chris Lattner8a2a3112001-12-14 16:52:21 +000011071 return 0;
11072}
11073
Chris Lattner0864acf2002-11-04 16:18:53 +000011074Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11075 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011076 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011077 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11078 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011079 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011080 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011081
11082 // Create and insert the replacement instruction...
11083 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011084 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011085 else {
11086 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011087 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011088 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011089 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011090
Chris Lattner0864acf2002-11-04 16:18:53 +000011091 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011092 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011093 //
11094 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011095 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011096
11097 // Now that I is pointing to the first non-allocation-inst in the block,
11098 // insert our getelementptr instruction...
11099 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011100 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011101 Value *Idx[2];
11102 Idx[0] = NullIdx;
11103 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011104 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11105 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011106 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011107
11108 // Now make everything use the getelementptr instead of the original
11109 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011110 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011111 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011112 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011113 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011114 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011115
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011116 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011117 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011118 // Note that we only do this for alloca's, because malloc should allocate
11119 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011120 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011121 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011122
11123 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11124 if (AI.getAlignment() == 0)
11125 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11126 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011127
Chris Lattner0864acf2002-11-04 16:18:53 +000011128 return 0;
11129}
11130
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011131Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11132 Value *Op = FI.getOperand(0);
11133
Chris Lattner17be6352004-10-18 02:59:09 +000011134 // free undef -> unreachable.
11135 if (isa<UndefValue>(Op)) {
11136 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011137 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011138 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011139 return EraseInstFromFunction(FI);
11140 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011141
Chris Lattner6160e852004-02-28 04:57:37 +000011142 // If we have 'free null' delete the instruction. This can happen in stl code
11143 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011144 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011145 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011146
11147 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11148 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11149 FI.setOperand(0, CI->getOperand(0));
11150 return &FI;
11151 }
11152
11153 // Change free (gep X, 0,0,0,0) into free(X)
11154 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11155 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011156 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011157 FI.setOperand(0, GEPI->getOperand(0));
11158 return &FI;
11159 }
11160 }
11161
11162 // Change free(malloc) into nothing, if the malloc has a single use.
11163 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11164 if (MI->hasOneUse()) {
11165 EraseInstFromFunction(FI);
11166 return EraseInstFromFunction(*MI);
11167 }
Chris Lattner6160e852004-02-28 04:57:37 +000011168
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011169 return 0;
11170}
11171
11172
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011173/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011174static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011175 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011176 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011177 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011178 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011179
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011180 if (TD) {
11181 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11182 // Instead of loading constant c string, use corresponding integer value
11183 // directly if string length is small enough.
11184 std::string Str;
11185 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11186 unsigned len = Str.length();
11187 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11188 unsigned numBits = Ty->getPrimitiveSizeInBits();
11189 // Replace LI with immediate integer store.
11190 if ((numBits >> 3) == len + 1) {
11191 APInt StrVal(numBits, 0);
11192 APInt SingleChar(numBits, 0);
11193 if (TD->isLittleEndian()) {
11194 for (signed i = len-1; i >= 0; i--) {
11195 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11196 StrVal = (StrVal << 8) | SingleChar;
11197 }
11198 } else {
11199 for (unsigned i = 0; i < len; i++) {
11200 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11201 StrVal = (StrVal << 8) | SingleChar;
11202 }
11203 // Append NULL at the end.
11204 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011205 StrVal = (StrVal << 8) | SingleChar;
11206 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011207 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011208 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011209 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011210 }
11211 }
11212 }
11213
Mon P Wang6753f952009-02-07 22:19:29 +000011214 const PointerType *DestTy = cast<PointerType>(CI->getType());
11215 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011216 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011217
11218 // If the address spaces don't match, don't eliminate the cast.
11219 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11220 return 0;
11221
Chris Lattnerb89e0712004-07-13 01:49:43 +000011222 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011223
Reid Spencer42230162007-01-22 05:51:25 +000011224 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011225 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011226 // If the source is an array, the code below will not succeed. Check to
11227 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11228 // constants.
11229 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11230 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11231 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011232 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011233 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011234 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011235 SrcTy = cast<PointerType>(CastOp->getType());
11236 SrcPTy = SrcTy->getElementType();
11237 }
11238
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011239 if (IC.getTargetData() &&
11240 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011241 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011242 // Do not allow turning this into a load of an integer, which is then
11243 // casted to a pointer, this pessimizes pointer analysis a lot.
11244 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011245 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11246 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011247
Chris Lattnerf9527852005-01-31 04:50:46 +000011248 // Okay, we are casting from one integer or pointer type to another of
11249 // the same size. Instead of casting the pointer before the load, cast
11250 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011251 Value *NewLoad =
11252 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011253 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011254 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011255 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011256 }
11257 }
11258 return 0;
11259}
11260
Chris Lattner833b8a42003-06-26 05:06:25 +000011261Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11262 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011263
Dan Gohman9941f742007-07-20 16:34:21 +000011264 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011265 if (TD) {
11266 unsigned KnownAlign =
11267 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11268 if (KnownAlign >
11269 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11270 LI.getAlignment()))
11271 LI.setAlignment(KnownAlign);
11272 }
Dan Gohman9941f742007-07-20 16:34:21 +000011273
Chris Lattner37366c12005-05-01 04:24:53 +000011274 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011275 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011276 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011277 return Res;
11278
11279 // None of the following transforms are legal for volatile loads.
11280 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011281
Dan Gohman2276a7b2008-10-15 23:19:35 +000011282 // Do really simple store-to-load forwarding and load CSE, to catch cases
11283 // where there are several consequtive memory accesses to the same location,
11284 // separated by a few arithmetic operations.
11285 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011286 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11287 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011288
Christopher Lambb15147e2007-12-29 07:56:53 +000011289 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11290 const Value *GEPI0 = GEPI->getOperand(0);
11291 // TODO: Consider a target hook for valid address spaces for this xform.
11292 if (isa<ConstantPointerNull>(GEPI0) &&
11293 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011294 // Insert a new store to null instruction before the load to indicate
11295 // that this code is not reachable. We do this instead of inserting
11296 // an unreachable instruction directly because we cannot modify the
11297 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011298 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011299 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011300 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011301 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011302 }
Chris Lattner37366c12005-05-01 04:24:53 +000011303
Chris Lattnere87597f2004-10-16 18:11:37 +000011304 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011305 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011306 // TODO: Consider a target hook for valid address spaces for this xform.
11307 if (isa<UndefValue>(C) || (C->isNullValue() &&
11308 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011309 // Insert a new store to null instruction before the load to indicate that
11310 // this code is not reachable. We do this instead of inserting an
11311 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011312 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011313 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011314 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011315 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011316
Chris Lattnere87597f2004-10-16 18:11:37 +000011317 // Instcombine load (constant global) into the value loaded.
11318 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011319 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011320 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011321
Chris Lattnere87597f2004-10-16 18:11:37 +000011322 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011324 if (CE->getOpcode() == Instruction::GetElementPtr) {
11325 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011326 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011327 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011328 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011329 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011330 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011331 if (CE->getOperand(0)->isNullValue()) {
11332 // Insert a new store to null instruction before the load to indicate
11333 // that this code is not reachable. We do this instead of inserting
11334 // an unreachable instruction directly because we cannot modify the
11335 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011336 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011337 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011338 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011339 }
11340
Reid Spencer3da59db2006-11-27 01:05:10 +000011341 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011342 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011343 return Res;
11344 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011345 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011346 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011347
11348 // If this load comes from anywhere in a constant global, and if the global
11349 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011350 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011351 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011352 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011353 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011354 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011355 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011356 }
11357 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011358
Chris Lattner37366c12005-05-01 04:24:53 +000011359 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011360 // Change select and PHI nodes to select values instead of addresses: this
11361 // helps alias analysis out a lot, allows many others simplifications, and
11362 // exposes redundancy in the code.
11363 //
11364 // Note that we cannot do the transformation unless we know that the
11365 // introduced loads cannot trap! Something like this is valid as long as
11366 // the condition is always false: load (select bool %C, int* null, int* %G),
11367 // but it would not be valid if we transformed it to load from null
11368 // unconditionally.
11369 //
11370 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11371 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011372 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11373 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011374 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11375 SI->getOperand(1)->getName()+".val");
11376 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11377 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011378 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011379 }
11380
Chris Lattner684fe212004-09-23 15:46:00 +000011381 // load (select (cond, null, P)) -> load P
11382 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11383 if (C->isNullValue()) {
11384 LI.setOperand(0, SI->getOperand(2));
11385 return &LI;
11386 }
11387
11388 // load (select (cond, P, null)) -> load P
11389 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11390 if (C->isNullValue()) {
11391 LI.setOperand(0, SI->getOperand(1));
11392 return &LI;
11393 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011394 }
11395 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011396 return 0;
11397}
11398
Reid Spencer55af2b52007-01-19 21:20:31 +000011399/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011400/// when possible. This makes it generally easy to do alias analysis and/or
11401/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011402static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11403 User *CI = cast<User>(SI.getOperand(1));
11404 Value *CastOp = CI->getOperand(0);
11405
11406 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011407 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11408 if (SrcTy == 0) return 0;
11409
11410 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011411
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011412 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11413 return 0;
11414
Chris Lattner3914f722009-01-24 01:00:13 +000011415 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11416 /// to its first element. This allows us to handle things like:
11417 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11418 /// on 32-bit hosts.
11419 SmallVector<Value*, 4> NewGEPIndices;
11420
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011421 // If the source is an array, the code below will not succeed. Check to
11422 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11423 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011424 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11425 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011426 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011427 NewGEPIndices.push_back(Zero);
11428
11429 while (1) {
11430 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011431 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011432 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011433 NewGEPIndices.push_back(Zero);
11434 SrcPTy = STy->getElementType(0);
11435 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11436 NewGEPIndices.push_back(Zero);
11437 SrcPTy = ATy->getElementType();
11438 } else {
11439 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011440 }
Chris Lattner3914f722009-01-24 01:00:13 +000011441 }
11442
Owen Andersondebcb012009-07-29 22:17:13 +000011443 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011444 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011445
11446 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11447 return 0;
11448
Chris Lattner71759c42009-01-16 20:12:52 +000011449 // If the pointers point into different address spaces or if they point to
11450 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011451 if (!IC.getTargetData() ||
11452 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011453 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011454 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11455 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011456 return 0;
11457
11458 // Okay, we are casting from one integer or pointer type to another of
11459 // the same size. Instead of casting the pointer before
11460 // the store, cast the value to be stored.
11461 Value *NewCast;
11462 Value *SIOp0 = SI.getOperand(0);
11463 Instruction::CastOps opcode = Instruction::BitCast;
11464 const Type* CastSrcTy = SIOp0->getType();
11465 const Type* CastDstTy = SrcPTy;
11466 if (isa<PointerType>(CastDstTy)) {
11467 if (CastSrcTy->isInteger())
11468 opcode = Instruction::IntToPtr;
11469 } else if (isa<IntegerType>(CastDstTy)) {
11470 if (isa<PointerType>(SIOp0->getType()))
11471 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011472 }
Chris Lattner3914f722009-01-24 01:00:13 +000011473
11474 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11475 // emit a GEP to index into its first field.
11476 if (!NewGEPIndices.empty()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011477 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11478 NewGEPIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011479 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011480 }
11481
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011482 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11483 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011484 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011485}
11486
Chris Lattner4aebaee2008-11-27 08:56:30 +000011487/// equivalentAddressValues - Test if A and B will obviously have the same
11488/// value. This includes recognizing that %t0 and %t1 will have the same
11489/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011490/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011491/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011492/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011493/// %t2 = load i32* %t1
11494///
11495static bool equivalentAddressValues(Value *A, Value *B) {
11496 // Test if the values are trivially equivalent.
11497 if (A == B) return true;
11498
11499 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011500 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11501 // its only used to compare two uses within the same basic block, which
11502 // means that they'll always either have the same value or one of them
11503 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011504 if (isa<BinaryOperator>(A) ||
11505 isa<CastInst>(A) ||
11506 isa<PHINode>(A) ||
11507 isa<GetElementPtrInst>(A))
11508 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011509 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011510 return true;
11511
11512 // Otherwise they may not be equivalent.
11513 return false;
11514}
11515
Dale Johannesen4945c652009-03-03 21:26:39 +000011516// If this instruction has two uses, one of which is a llvm.dbg.declare,
11517// return the llvm.dbg.declare.
11518DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11519 if (!V->hasNUses(2))
11520 return 0;
11521 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11522 UI != E; ++UI) {
11523 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11524 return DI;
11525 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11526 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11527 return DI;
11528 }
11529 }
11530 return 0;
11531}
11532
Chris Lattner2f503e62005-01-31 05:36:43 +000011533Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11534 Value *Val = SI.getOperand(0);
11535 Value *Ptr = SI.getOperand(1);
11536
11537 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011538 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011539 ++NumCombined;
11540 return 0;
11541 }
Chris Lattner836692d2007-01-15 06:51:56 +000011542
11543 // If the RHS is an alloca with a single use, zapify the store, making the
11544 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011545 // If the RHS is an alloca with a two uses, the other one being a
11546 // llvm.dbg.declare, zapify the store and the declare, making the
11547 // alloca dead. We must do this to prevent declare's from affecting
11548 // codegen.
11549 if (!SI.isVolatile()) {
11550 if (Ptr->hasOneUse()) {
11551 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011552 EraseInstFromFunction(SI);
11553 ++NumCombined;
11554 return 0;
11555 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011556 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11557 if (isa<AllocaInst>(GEP->getOperand(0))) {
11558 if (GEP->getOperand(0)->hasOneUse()) {
11559 EraseInstFromFunction(SI);
11560 ++NumCombined;
11561 return 0;
11562 }
11563 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11564 EraseInstFromFunction(*DI);
11565 EraseInstFromFunction(SI);
11566 ++NumCombined;
11567 return 0;
11568 }
11569 }
11570 }
11571 }
11572 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11573 EraseInstFromFunction(*DI);
11574 EraseInstFromFunction(SI);
11575 ++NumCombined;
11576 return 0;
11577 }
Chris Lattner836692d2007-01-15 06:51:56 +000011578 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011579
Dan Gohman9941f742007-07-20 16:34:21 +000011580 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011581 if (TD) {
11582 unsigned KnownAlign =
11583 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11584 if (KnownAlign >
11585 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11586 SI.getAlignment()))
11587 SI.setAlignment(KnownAlign);
11588 }
Dan Gohman9941f742007-07-20 16:34:21 +000011589
Dale Johannesenacb51a32009-03-03 01:43:03 +000011590 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011591 // stores to the same location, separated by a few arithmetic operations. This
11592 // situation often occurs with bitfield accesses.
11593 BasicBlock::iterator BBI = &SI;
11594 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11595 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011596 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011597 // Don't count debug info directives, lest they affect codegen,
11598 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11599 // It is necessary for correctness to skip those that feed into a
11600 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011601 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011602 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011603 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011604 continue;
11605 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011606
11607 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11608 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011609 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11610 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011611 ++NumDeadStore;
11612 ++BBI;
11613 EraseInstFromFunction(*PrevSI);
11614 continue;
11615 }
11616 break;
11617 }
11618
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011619 // If this is a load, we have to stop. However, if the loaded value is from
11620 // the pointer we're loading and is producing the pointer we're storing,
11621 // then *this* store is dead (X = load P; store X -> P).
11622 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011623 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11624 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011625 EraseInstFromFunction(SI);
11626 ++NumCombined;
11627 return 0;
11628 }
11629 // Otherwise, this is a load from some other location. Stores before it
11630 // may not be dead.
11631 break;
11632 }
11633
Chris Lattner9ca96412006-02-08 03:25:32 +000011634 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011635 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011636 break;
11637 }
11638
11639
11640 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011641
11642 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011643 if (isa<ConstantPointerNull>(Ptr) &&
11644 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011645 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011646 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011647 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011648 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011649 ++NumCombined;
11650 }
11651 return 0; // Do not modify these!
11652 }
11653
11654 // store undef, Ptr -> noop
11655 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011656 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011657 ++NumCombined;
11658 return 0;
11659 }
11660
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011661 // If the pointer destination is a cast, see if we can fold the cast into the
11662 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011663 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011664 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11665 return Res;
11666 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011667 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011668 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11669 return Res;
11670
Chris Lattner408902b2005-09-12 23:23:25 +000011671
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011672 // If this store is the last instruction in the basic block (possibly
11673 // excepting debug info instructions and the pointer bitcasts that feed
11674 // into them), and if the block ends with an unconditional branch, try
11675 // to move it to the successor block.
11676 BBI = &SI;
11677 do {
11678 ++BBI;
11679 } while (isa<DbgInfoIntrinsic>(BBI) ||
11680 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011681 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011682 if (BI->isUnconditional())
11683 if (SimplifyStoreAtEndOfBlock(SI))
11684 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011685
Chris Lattner2f503e62005-01-31 05:36:43 +000011686 return 0;
11687}
11688
Chris Lattner3284d1f2007-04-15 00:07:55 +000011689/// SimplifyStoreAtEndOfBlock - Turn things like:
11690/// if () { *P = v1; } else { *P = v2 }
11691/// into a phi node with a store in the successor.
11692///
Chris Lattner31755a02007-04-15 01:02:18 +000011693/// Simplify things like:
11694/// *P = v1; if () { *P = v2; }
11695/// into a phi node with a store in the successor.
11696///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011697bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11698 BasicBlock *StoreBB = SI.getParent();
11699
11700 // Check to see if the successor block has exactly two incoming edges. If
11701 // so, see if the other predecessor contains a store to the same location.
11702 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011703 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011704
11705 // Determine whether Dest has exactly two predecessors and, if so, compute
11706 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011707 pred_iterator PI = pred_begin(DestBB);
11708 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011709 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011710 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011711 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011712 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011713 return false;
11714
11715 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011716 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011717 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011718 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011719 }
Chris Lattner31755a02007-04-15 01:02:18 +000011720 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011721 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011722
11723 // Bail out if all the relevant blocks aren't distinct (this can happen,
11724 // for example, if SI is in an infinite loop)
11725 if (StoreBB == DestBB || OtherBB == DestBB)
11726 return false;
11727
Chris Lattner31755a02007-04-15 01:02:18 +000011728 // Verify that the other block ends in a branch and is not otherwise empty.
11729 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011730 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011731 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011732 return false;
11733
Chris Lattner31755a02007-04-15 01:02:18 +000011734 // If the other block ends in an unconditional branch, check for the 'if then
11735 // else' case. there is an instruction before the branch.
11736 StoreInst *OtherStore = 0;
11737 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011738 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011739 // Skip over debugging info.
11740 while (isa<DbgInfoIntrinsic>(BBI) ||
11741 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11742 if (BBI==OtherBB->begin())
11743 return false;
11744 --BBI;
11745 }
11746 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011747 OtherStore = dyn_cast<StoreInst>(BBI);
11748 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11749 return false;
11750 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011751 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011752 // destinations is StoreBB, then we have the if/then case.
11753 if (OtherBr->getSuccessor(0) != StoreBB &&
11754 OtherBr->getSuccessor(1) != StoreBB)
11755 return false;
11756
11757 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011758 // if/then triangle. See if there is a store to the same ptr as SI that
11759 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011760 for (;; --BBI) {
11761 // Check to see if we find the matching store.
11762 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11763 if (OtherStore->getOperand(1) != SI.getOperand(1))
11764 return false;
11765 break;
11766 }
Eli Friedman6903a242008-06-13 22:02:12 +000011767 // If we find something that may be using or overwriting the stored
11768 // value, or if we run out of instructions, we can't do the xform.
11769 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011770 BBI == OtherBB->begin())
11771 return false;
11772 }
11773
11774 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011775 // make sure nothing reads or overwrites the stored value in
11776 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011777 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11778 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011779 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011780 return false;
11781 }
11782 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011783
Chris Lattner31755a02007-04-15 01:02:18 +000011784 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011785 Value *MergedVal = OtherStore->getOperand(0);
11786 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011787 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011788 PN->reserveOperandSpace(2);
11789 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011790 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11791 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011792 }
11793
11794 // Advance to a place where it is safe to insert the new store and
11795 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011796 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011797 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11798 OtherStore->isVolatile()), *BBI);
11799
11800 // Nuke the old stores.
11801 EraseInstFromFunction(SI);
11802 EraseInstFromFunction(*OtherStore);
11803 ++NumCombined;
11804 return true;
11805}
11806
Chris Lattner2f503e62005-01-31 05:36:43 +000011807
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011808Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11809 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011810 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011811 BasicBlock *TrueDest;
11812 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011813 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011814 !isa<Constant>(X)) {
11815 // Swap Destinations and condition...
11816 BI.setCondition(X);
11817 BI.setSuccessor(0, FalseDest);
11818 BI.setSuccessor(1, TrueDest);
11819 return &BI;
11820 }
11821
Reid Spencere4d87aa2006-12-23 06:05:41 +000011822 // Cannonicalize fcmp_one -> fcmp_oeq
11823 FCmpInst::Predicate FPred; Value *Y;
11824 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011825 TrueDest, FalseDest)) &&
11826 BI.getCondition()->hasOneUse())
11827 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11828 FPred == FCmpInst::FCMP_OGE) {
11829 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11830 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11831
11832 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011833 BI.setSuccessor(0, FalseDest);
11834 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011835 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011836 return &BI;
11837 }
11838
11839 // Cannonicalize icmp_ne -> icmp_eq
11840 ICmpInst::Predicate IPred;
11841 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011842 TrueDest, FalseDest)) &&
11843 BI.getCondition()->hasOneUse())
11844 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11845 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11846 IPred == ICmpInst::ICMP_SGE) {
11847 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11848 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11849 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011850 BI.setSuccessor(0, FalseDest);
11851 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011852 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011853 return &BI;
11854 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011855
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011856 return 0;
11857}
Chris Lattner0864acf2002-11-04 16:18:53 +000011858
Chris Lattner46238a62004-07-03 00:26:11 +000011859Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11860 Value *Cond = SI.getCondition();
11861 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11862 if (I->getOpcode() == Instruction::Add)
11863 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11864 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11865 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011866 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011867 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011868 AddRHS));
11869 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011870 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011871 return &SI;
11872 }
11873 }
11874 return 0;
11875}
11876
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011877Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011878 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011879
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011880 if (!EV.hasIndices())
11881 return ReplaceInstUsesWith(EV, Agg);
11882
11883 if (Constant *C = dyn_cast<Constant>(Agg)) {
11884 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011885 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011886
11887 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011888 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011889
11890 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11891 // Extract the element indexed by the first index out of the constant
11892 Value *V = C->getOperand(*EV.idx_begin());
11893 if (EV.getNumIndices() > 1)
11894 // Extract the remaining indices out of the constant indexed by the
11895 // first index
11896 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11897 else
11898 return ReplaceInstUsesWith(EV, V);
11899 }
11900 return 0; // Can't handle other constants
11901 }
11902 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11903 // We're extracting from an insertvalue instruction, compare the indices
11904 const unsigned *exti, *exte, *insi, *inse;
11905 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11906 exte = EV.idx_end(), inse = IV->idx_end();
11907 exti != exte && insi != inse;
11908 ++exti, ++insi) {
11909 if (*insi != *exti)
11910 // The insert and extract both reference distinctly different elements.
11911 // This means the extract is not influenced by the insert, and we can
11912 // replace the aggregate operand of the extract with the aggregate
11913 // operand of the insert. i.e., replace
11914 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11915 // %E = extractvalue { i32, { i32 } } %I, 0
11916 // with
11917 // %E = extractvalue { i32, { i32 } } %A, 0
11918 return ExtractValueInst::Create(IV->getAggregateOperand(),
11919 EV.idx_begin(), EV.idx_end());
11920 }
11921 if (exti == exte && insi == inse)
11922 // Both iterators are at the end: Index lists are identical. Replace
11923 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11924 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11925 // with "i32 42"
11926 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11927 if (exti == exte) {
11928 // The extract list is a prefix of the insert list. i.e. replace
11929 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11930 // %E = extractvalue { i32, { i32 } } %I, 1
11931 // with
11932 // %X = extractvalue { i32, { i32 } } %A, 1
11933 // %E = insertvalue { i32 } %X, i32 42, 0
11934 // by switching the order of the insert and extract (though the
11935 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011936 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11937 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011938 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11939 insi, inse);
11940 }
11941 if (insi == inse)
11942 // The insert list is a prefix of the extract list
11943 // We can simply remove the common indices from the extract and make it
11944 // operate on the inserted value instead of the insertvalue result.
11945 // i.e., replace
11946 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11947 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11948 // with
11949 // %E extractvalue { i32 } { i32 42 }, 0
11950 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11951 exti, exte);
11952 }
11953 // Can't simplify extracts from other values. Note that nested extracts are
11954 // already simplified implicitely by the above (extract ( extract (insert) )
11955 // will be translated into extract ( insert ( extract ) ) first and then just
11956 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011957 return 0;
11958}
11959
Chris Lattner220b0cf2006-03-05 00:22:33 +000011960/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11961/// is to leave as a vector operation.
11962static bool CheapToScalarize(Value *V, bool isConstant) {
11963 if (isa<ConstantAggregateZero>(V))
11964 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000011965 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000011966 if (isConstant) return true;
11967 // If all elts are the same, we can extract.
11968 Constant *Op0 = C->getOperand(0);
11969 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11970 if (C->getOperand(i) != Op0)
11971 return false;
11972 return true;
11973 }
11974 Instruction *I = dyn_cast<Instruction>(V);
11975 if (!I) return false;
11976
11977 // Insert element gets simplified to the inserted element or is deleted if
11978 // this is constant idx extract element and its a constant idx insertelt.
11979 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11980 isa<ConstantInt>(I->getOperand(2)))
11981 return true;
11982 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11983 return true;
11984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11985 if (BO->hasOneUse() &&
11986 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11987 CheapToScalarize(BO->getOperand(1), isConstant)))
11988 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011989 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11990 if (CI->hasOneUse() &&
11991 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11992 CheapToScalarize(CI->getOperand(1), isConstant)))
11993 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000011994
11995 return false;
11996}
11997
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000011998/// Read and decode a shufflevector mask.
11999///
12000/// It turns undef elements into values that are larger than the number of
12001/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012002static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12003 unsigned NElts = SVI->getType()->getNumElements();
12004 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12005 return std::vector<unsigned>(NElts, 0);
12006 if (isa<UndefValue>(SVI->getOperand(2)))
12007 return std::vector<unsigned>(NElts, 2*NElts);
12008
12009 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012010 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012011 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12012 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012013 Result.push_back(NElts*2); // undef -> 8
12014 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012015 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012016 return Result;
12017}
12018
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012019/// FindScalarElement - Given a vector and an element number, see if the scalar
12020/// value is already around as a register, for example if it were inserted then
12021/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012022static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012023 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012024 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12025 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012026 unsigned Width = PTy->getNumElements();
12027 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012028 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012029
12030 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012031 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012032 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012033 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012034 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012035 return CP->getOperand(EltNo);
12036 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12037 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012038 if (!isa<ConstantInt>(III->getOperand(2)))
12039 return 0;
12040 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012041
12042 // If this is an insert to the element we are looking for, return the
12043 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012044 if (EltNo == IIElt)
12045 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012046
12047 // Otherwise, the insertelement doesn't modify the value, recurse on its
12048 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012049 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012050 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012051 unsigned LHSWidth =
12052 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012053 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012054 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012055 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012056 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012057 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012058 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012059 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012060 }
12061
12062 // Otherwise, we don't know.
12063 return 0;
12064}
12065
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012066Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012067 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012068 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012069 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012070
Dan Gohman07a96762007-07-16 14:29:03 +000012071 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012072 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012073 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012074
Reid Spencer9d6565a2007-02-15 02:26:10 +000012075 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012076 // If vector val is constant with all elements the same, replace EI with
12077 // that element. When the elements are not identical, we cannot replace yet
12078 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012079 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012080 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012081 if (C->getOperand(i) != op0) {
12082 op0 = 0;
12083 break;
12084 }
12085 if (op0)
12086 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012087 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012088
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012089 // If extracting a specified index from the vector, see if we can recursively
12090 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012091 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012092 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012093 unsigned VectorWidth =
12094 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012095
12096 // If this is extracting an invalid index, turn this into undef, to avoid
12097 // crashing the code below.
12098 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012099 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012100
Chris Lattner867b99f2006-10-05 06:55:50 +000012101 // This instruction only demands the single element from the input vector.
12102 // If the input vector has a single use, simplify it based on this use
12103 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012104 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012105 APInt UndefElts(VectorWidth, 0);
12106 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012107 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012108 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012109 EI.setOperand(0, V);
12110 return &EI;
12111 }
12112 }
12113
Owen Andersond672ecb2009-07-03 00:17:18 +000012114 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012115 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012116
12117 // If the this extractelement is directly using a bitcast from a vector of
12118 // the same number of elements, see if we can find the source element from
12119 // it. In this case, we will end up needing to bitcast the scalars.
12120 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12121 if (const VectorType *VT =
12122 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12123 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012124 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12125 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012126 return new BitCastInst(Elt, EI.getType());
12127 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012128 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012129
Chris Lattner73fa49d2006-05-25 22:53:38 +000012130 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012131 if (I->hasOneUse()) {
12132 // Push extractelement into predecessor operation if legal and
12133 // profitable to do so
12134 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012135 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12136 if (CheapToScalarize(BO, isConstantElt)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012137 Value *newEI0 =
12138 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12139 EI.getName()+".lhs");
12140 Value *newEI1 =
12141 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12142 EI.getName()+".rhs");
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012143 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012144 }
Chris Lattner08142f22009-08-30 19:47:22 +000012145 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12146 unsigned AS = LI->getPointerAddressSpace();
12147 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12148 PointerType::get(EI.getType(), AS),
12149 I->getOperand(0)->getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012150 Value *GEP =
12151 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012152 cast<GEPOperator>(GEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012153
12154 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12155
12156 // Make sure the Load goes before the load instruction in the source,
12157 // not wherever the extract happens to be.
Chris Lattner08142f22009-08-30 19:47:22 +000012158 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12159 P->moveBefore(I);
12160 if (Instruction *G = dyn_cast<Instruction>(GEP))
12161 G->moveBefore(I);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012162 Load->moveBefore(I);
12163
Mon P Wang7c4efa62009-08-13 05:12:13 +000012164 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012165 }
12166 }
12167 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12168 // Extracting the inserted element?
12169 if (IE->getOperand(2) == EI.getOperand(1))
12170 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12171 // If the inserted and extracted elements are constants, they must not
12172 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000012173 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012174 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012175 EI.setOperand(0, IE->getOperand(0));
12176 return &EI;
12177 }
12178 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12179 // If this is extracting an element from a shufflevector, figure out where
12180 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012181 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12182 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012183 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012184 unsigned LHSWidth =
12185 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12186
12187 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012188 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012189 else if (SrcIdx < LHSWidth*2) {
12190 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012191 Src = SVI->getOperand(1);
12192 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012193 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012194 }
Eric Christophera3500da2009-07-25 02:28:41 +000012195 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000012196 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12197 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012198 }
12199 }
Eli Friedman2451a642009-07-18 23:06:53 +000012200 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012201 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012202 return 0;
12203}
12204
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012205/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12206/// elements from either LHS or RHS, return the shuffle mask and true.
12207/// Otherwise, return false.
12208static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012209 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012210 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012211 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12212 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012213 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012214
12215 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012216 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012217 return true;
12218 } else if (V == LHS) {
12219 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012220 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012221 return true;
12222 } else if (V == RHS) {
12223 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012224 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012225 return true;
12226 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12227 // If this is an insert of an extract from some other vector, include it.
12228 Value *VecOp = IEI->getOperand(0);
12229 Value *ScalarOp = IEI->getOperand(1);
12230 Value *IdxOp = IEI->getOperand(2);
12231
Chris Lattnerd929f062006-04-27 21:14:21 +000012232 if (!isa<ConstantInt>(IdxOp))
12233 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012234 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012235
12236 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12237 // Okay, we can handle this if the vector we are insertinting into is
12238 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012239 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012240 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012241 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012242 return true;
12243 }
12244 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12245 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012246 EI->getOperand(0)->getType() == V->getType()) {
12247 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012248 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012249
12250 // This must be extracting from either LHS or RHS.
12251 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12252 // Okay, we can handle this if the vector we are insertinting into is
12253 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012254 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012255 // If so, update the mask to reflect the inserted value.
12256 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012257 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012258 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012259 } else {
12260 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012261 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012262 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012263
12264 }
12265 return true;
12266 }
12267 }
12268 }
12269 }
12270 }
12271 // TODO: Handle shufflevector here!
12272
12273 return false;
12274}
12275
12276/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12277/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12278/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012279static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012280 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012281 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012282 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012283 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012284 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012285
12286 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012287 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012288 return V;
12289 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012290 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012291 return V;
12292 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12293 // If this is an insert of an extract from some other vector, include it.
12294 Value *VecOp = IEI->getOperand(0);
12295 Value *ScalarOp = IEI->getOperand(1);
12296 Value *IdxOp = IEI->getOperand(2);
12297
12298 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12299 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12300 EI->getOperand(0)->getType() == V->getType()) {
12301 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012302 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12303 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012304
12305 // Either the extracted from or inserted into vector must be RHSVec,
12306 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012307 if (EI->getOperand(0) == RHS || RHS == 0) {
12308 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012309 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012310 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012311 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012312 return V;
12313 }
12314
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012315 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012316 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12317 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012318 // Everything but the extracted element is replaced with the RHS.
12319 for (unsigned i = 0; i != NumElts; ++i) {
12320 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012321 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012322 }
12323 return V;
12324 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012325
12326 // If this insertelement is a chain that comes from exactly these two
12327 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012328 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12329 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012330 return EI->getOperand(0);
12331
Chris Lattnerefb47352006-04-15 01:39:45 +000012332 }
12333 }
12334 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012335 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012336
12337 // Otherwise, can't do anything fancy. Return an identity vector.
12338 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012339 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012340 return V;
12341}
12342
12343Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12344 Value *VecOp = IE.getOperand(0);
12345 Value *ScalarOp = IE.getOperand(1);
12346 Value *IdxOp = IE.getOperand(2);
12347
Chris Lattner599ded12007-04-09 01:11:16 +000012348 // Inserting an undef or into an undefined place, remove this.
12349 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12350 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012351
Chris Lattnerefb47352006-04-15 01:39:45 +000012352 // If the inserted element was extracted from some other vector, and if the
12353 // indexes are constant, try to turn this into a shufflevector operation.
12354 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12355 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12356 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012357 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012358 unsigned ExtractedIdx =
12359 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012360 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012361
12362 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12363 return ReplaceInstUsesWith(IE, VecOp);
12364
12365 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012366 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012367
12368 // If we are extracting a value from a vector, then inserting it right
12369 // back into the same place, just use the input vector.
12370 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12371 return ReplaceInstUsesWith(IE, VecOp);
12372
12373 // We could theoretically do this for ANY input. However, doing so could
12374 // turn chains of insertelement instructions into a chain of shufflevector
12375 // instructions, and right now we do not merge shufflevectors. As such,
12376 // only do this in a situation where it is clear that there is benefit.
12377 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12378 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12379 // the values of VecOp, except then one read from EIOp0.
12380 // Build a new shuffle mask.
12381 std::vector<Constant*> Mask;
12382 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012383 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012384 else {
12385 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012386 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012387 NumVectorElts));
12388 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012389 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012390 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012391 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012392 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012393 }
12394
12395 // If this insertelement isn't used by some other insertelement, turn it
12396 // (and any insertelements it points to), into one big shuffle.
12397 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12398 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012399 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012400 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012401 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012402 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012403 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012404 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012405 }
12406 }
12407 }
12408
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012409 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12410 APInt UndefElts(VWidth, 0);
12411 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12412 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12413 return &IE;
12414
Chris Lattnerefb47352006-04-15 01:39:45 +000012415 return 0;
12416}
12417
12418
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012419Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12420 Value *LHS = SVI.getOperand(0);
12421 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012422 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012423
12424 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012425
Chris Lattner867b99f2006-10-05 06:55:50 +000012426 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012427 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012428 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012429
Dan Gohman488fbfc2008-09-09 18:11:14 +000012430 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012431
12432 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12433 return 0;
12434
Evan Cheng388df622009-02-03 10:05:09 +000012435 APInt UndefElts(VWidth, 0);
12436 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12437 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012438 LHS = SVI.getOperand(0);
12439 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012440 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012441 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012442
Chris Lattner863bcff2006-05-25 23:48:38 +000012443 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12444 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12445 if (LHS == RHS || isa<UndefValue>(LHS)) {
12446 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012447 // shuffle(undef,undef,mask) -> undef.
12448 return ReplaceInstUsesWith(SVI, LHS);
12449 }
12450
Chris Lattner863bcff2006-05-25 23:48:38 +000012451 // Remap any references to RHS to use LHS.
12452 std::vector<Constant*> Elts;
12453 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012454 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012455 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012456 else {
12457 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012458 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012459 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012460 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012461 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012462 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012463 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012464 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012465 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012466 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012467 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012468 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012469 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012470 LHS = SVI.getOperand(0);
12471 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012472 MadeChange = true;
12473 }
12474
Chris Lattner7b2e27922006-05-26 00:29:06 +000012475 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012476 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012477
Chris Lattner863bcff2006-05-25 23:48:38 +000012478 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12479 if (Mask[i] >= e*2) continue; // Ignore undef values.
12480 // Is this an identity shuffle of the LHS value?
12481 isLHSID &= (Mask[i] == i);
12482
12483 // Is this an identity shuffle of the RHS value?
12484 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012485 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012486
Chris Lattner863bcff2006-05-25 23:48:38 +000012487 // Eliminate identity shuffles.
12488 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12489 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012490
Chris Lattner7b2e27922006-05-26 00:29:06 +000012491 // If the LHS is a shufflevector itself, see if we can combine it with this
12492 // one without producing an unusual shuffle. Here we are really conservative:
12493 // we are absolutely afraid of producing a shuffle mask not in the input
12494 // program, because the code gen may not be smart enough to turn a merged
12495 // shuffle into two specific shuffles: it may produce worse code. As such,
12496 // we only merge two shuffles if the result is one of the two input shuffle
12497 // masks. In this case, merging the shuffles just removes one instruction,
12498 // which we know is safe. This is good for things like turning:
12499 // (splat(splat)) -> splat.
12500 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12501 if (isa<UndefValue>(RHS)) {
12502 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12503
12504 std::vector<unsigned> NewMask;
12505 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12506 if (Mask[i] >= 2*e)
12507 NewMask.push_back(2*e);
12508 else
12509 NewMask.push_back(LHSMask[Mask[i]]);
12510
12511 // If the result mask is equal to the src shuffle or this shuffle mask, do
12512 // the replacement.
12513 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012514 unsigned LHSInNElts =
12515 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012516 std::vector<Constant*> Elts;
12517 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012518 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012519 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012520 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012521 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012522 }
12523 }
12524 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12525 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012526 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012527 }
12528 }
12529 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012530
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012531 return MadeChange ? &SVI : 0;
12532}
12533
12534
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012535
Chris Lattnerea1c4542004-12-08 23:43:58 +000012536
12537/// TryToSinkInstruction - Try to move the specified instruction from its
12538/// current block into the beginning of DestBlock, which can only happen if it's
12539/// safe to move the instruction past all of the instructions between it and the
12540/// end of its block.
12541static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12542 assert(I->hasOneUse() && "Invariants didn't hold!");
12543
Chris Lattner108e9022005-10-27 17:13:11 +000012544 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012545 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012546 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012547
Chris Lattnerea1c4542004-12-08 23:43:58 +000012548 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012549 if (isa<AllocaInst>(I) && I->getParent() ==
12550 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012551 return false;
12552
Chris Lattner96a52a62004-12-09 07:14:34 +000012553 // We can only sink load instructions if there is nothing between the load and
12554 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012555 if (I->mayReadFromMemory()) {
12556 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012557 Scan != E; ++Scan)
12558 if (Scan->mayWriteToMemory())
12559 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012560 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012561
Dan Gohman02dea8b2008-05-23 21:05:58 +000012562 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012563
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012564 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012565 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012566 ++NumSunkInst;
12567 return true;
12568}
12569
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012570
12571/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12572/// all reachable code to the worklist.
12573///
12574/// This has a couple of tricks to make the code faster and more powerful. In
12575/// particular, we constant fold and DCE instructions as we go, to avoid adding
12576/// them to the worklist (this significantly speeds up instcombine on code where
12577/// many instructions are dead or constant). Additionally, if we find a branch
12578/// whose condition is a known constant, we only visit the reachable successors.
12579///
12580static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012581 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012582 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012583 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012584 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012585 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012586
Chris Lattner2c7718a2007-03-23 19:17:18 +000012587 while (!Worklist.empty()) {
12588 BB = Worklist.back();
12589 Worklist.pop_back();
12590
12591 // We have now visited this block! If we've already been here, ignore it.
12592 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012593
12594 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012595 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12596 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012597
Chris Lattner2c7718a2007-03-23 19:17:18 +000012598 // DCE instruction if trivially dead.
12599 if (isInstructionTriviallyDead(Inst)) {
12600 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012601 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012602 Inst->eraseFromParent();
12603 continue;
12604 }
12605
12606 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012607 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012608 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12609 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012610 Inst->replaceAllUsesWith(C);
12611 ++NumConstProp;
12612 Inst->eraseFromParent();
12613 continue;
12614 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012615
Devang Patel7fe1dec2008-11-19 18:56:50 +000012616 // If there are two consecutive llvm.dbg.stoppoint calls then
12617 // it is likely that the optimizer deleted code in between these
12618 // two intrinsics.
12619 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12620 if (DBI_Next) {
12621 if (DBI_Prev
12622 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12623 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012624 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012625 DBI_Prev->eraseFromParent();
12626 }
12627 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012628 } else {
12629 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012630 }
12631
Chris Lattner7a1e9242009-08-30 06:13:40 +000012632 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012633 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012634
12635 // Recursively visit successors. If this is a branch or switch on a
12636 // constant, only visit the reachable successor.
12637 TerminatorInst *TI = BB->getTerminator();
12638 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12639 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12640 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012641 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012642 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012643 continue;
12644 }
12645 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12646 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12647 // See if this is an explicit destination.
12648 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12649 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012650 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012651 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012652 continue;
12653 }
12654
12655 // Otherwise it is the default destination.
12656 Worklist.push_back(SI->getSuccessor(0));
12657 continue;
12658 }
12659 }
12660
12661 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12662 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012663 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012664}
12665
Chris Lattnerec9c3582007-03-03 02:04:50 +000012666bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012667 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012668 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012669
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012670 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12671 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012672
Chris Lattnerb3d59702005-07-07 20:40:38 +000012673 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012674 // Do a depth-first traversal of the function, populate the worklist with
12675 // the reachable instructions. Ignore blocks that are not reachable. Keep
12676 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012677 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012678 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012679
Chris Lattnerb3d59702005-07-07 20:40:38 +000012680 // Do a quick scan over the function. If we find any blocks that are
12681 // unreachable, remove any instructions inside of them. This prevents
12682 // the instcombine code from having to deal with some bad special cases.
12683 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12684 if (!Visited.count(BB)) {
12685 Instruction *Term = BB->getTerminator();
12686 while (Term != BB->begin()) { // Remove instrs bottom-up
12687 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012688
Chris Lattnerbdff5482009-08-23 04:37:46 +000012689 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012690 // A debug intrinsic shouldn't force another iteration if we weren't
12691 // going to do one without it.
12692 if (!isa<DbgInfoIntrinsic>(I)) {
12693 ++NumDeadInst;
12694 Changed = true;
12695 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012696 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012697 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012698 I->eraseFromParent();
12699 }
12700 }
12701 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012702
Chris Lattner873ff012009-08-30 05:55:36 +000012703 while (!Worklist.isEmpty()) {
12704 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012705 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012706
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012707 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012708 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012709 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012710 EraseInstFromFunction(*I);
12711 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012712 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012713 continue;
12714 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012715
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012716 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012717 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012718 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012719
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012720 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012721 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012722 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012723 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012724 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012725 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012726 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012727
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012728 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012729 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012730 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12731 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012732 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12733 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012734 if (NewC != CE) {
12735 i->set(NewC);
12736 Changed = true;
12737 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012738 }
12739
Chris Lattnerea1c4542004-12-08 23:43:58 +000012740 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012741 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012742 BasicBlock *BB = I->getParent();
12743 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12744 if (UserParent != BB) {
12745 bool UserIsSuccessor = false;
12746 // See if the user is one of our successors.
12747 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12748 if (*SI == UserParent) {
12749 UserIsSuccessor = true;
12750 break;
12751 }
12752
12753 // If the user is one of our immediate successors, and if that successor
12754 // only has us as a predecessors (we'd have to split the critical edge
12755 // otherwise), we can keep going.
12756 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12757 next(pred_begin(UserParent)) == pred_end(UserParent))
12758 // Okay, the CFG is simple enough, try to sink this instruction.
12759 Changed |= TryToSinkInstruction(I, UserParent);
12760 }
12761 }
12762
Chris Lattner74381062009-08-30 07:44:24 +000012763 // Now that we have an instruction, try combining it to simplify it.
12764 Builder->SetInsertPoint(I->getParent(), I);
12765
Reid Spencera9b81012007-03-26 17:44:01 +000012766#ifndef NDEBUG
12767 std::string OrigI;
12768#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012769 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012770
Chris Lattner90ac28c2002-08-02 19:29:35 +000012771 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012772 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012773 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012774 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012775 DEBUG(errs() << "IC: Old = " << *I << '\n'
12776 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012777
Chris Lattnerf523d062004-06-09 05:08:07 +000012778 // Everything uses the new instruction now.
12779 I->replaceAllUsesWith(Result);
12780
12781 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012782 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012783 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012784
Chris Lattner6934a042007-02-11 01:23:03 +000012785 // Move the name to the new instruction first.
12786 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012787
12788 // Insert the new instruction into the basic block...
12789 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012790 BasicBlock::iterator InsertPos = I;
12791
12792 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12793 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12794 ++InsertPos;
12795
12796 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012797
Chris Lattner7a1e9242009-08-30 06:13:40 +000012798 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012799 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012800#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012801 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12802 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012803#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012804
Chris Lattner90ac28c2002-08-02 19:29:35 +000012805 // If the instruction was modified, it's possible that it is now dead.
12806 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012807 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012808 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012809 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012810 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012811 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012812 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012813 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012814 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012815 }
12816 }
12817
Chris Lattner873ff012009-08-30 05:55:36 +000012818 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012819 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012820}
12821
Chris Lattnerec9c3582007-03-03 02:04:50 +000012822
12823bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012824 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012825 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012826
Chris Lattner74381062009-08-30 07:44:24 +000012827
12828 /// Builder - This is an IRBuilder that automatically inserts new
12829 /// instructions into the worklist when they are created.
12830 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12831 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12832 InstCombineIRInserter(Worklist));
12833 Builder = &TheBuilder;
12834
Chris Lattnerec9c3582007-03-03 02:04:50 +000012835 bool EverMadeChange = false;
12836
12837 // Iterate while there is work to do.
12838 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012839 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012840 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012841
12842 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012843 return EverMadeChange;
12844}
12845
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012846FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012847 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012848}