blob: 4b66015380a215848ec123ca4d3e9ecdfa8cfba0 [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 }
306
Chris Lattner0c967662004-09-24 15:21:34 +0000307 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
308 /// This also adds the cast to the worklist. Finally, this returns the
309 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000310 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
311 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000312 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000313
Chris Lattnere2ed0572006-04-06 19:19:17 +0000314 if (Constant *CV = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000315 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000316
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000317 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000318 Worklist.Add(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000319 return C;
320 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000321
322 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
323 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
324 }
325
Chris Lattner0c967662004-09-24 15:21:34 +0000326
Chris Lattner8b170942002-08-09 23:47:40 +0000327 // ReplaceInstUsesWith - This method is to be used when an instruction is
328 // found to be dead, replacable with another preexisting expression. Here
329 // we add all uses of I to the worklist, replace all uses of I with the new
330 // value, then return I, so that the inst combiner will know that I was
331 // modified.
332 //
333 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000334 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000335
336 // If we are replacing the instruction with itself, this must be in a
337 // segment of unreachable code, so just clobber the instruction.
338 if (&I == V)
339 V = UndefValue::get(I.getType());
340
341 I.replaceAllUsesWith(V);
342 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000343 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000344
345 // EraseInstFromFunction - When dealing with an instruction that has side
346 // effects or produces a void value, we can't rely on DCE to delete the
347 // instruction. Instead, visit methods should return the value returned by
348 // this function.
349 Instruction *EraseInstFromFunction(Instruction &I) {
350 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000351 // Make sure that we reprocess all operands now that we reduced their
352 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000353 if (I.getNumOperands() < 8) {
354 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355 if (Instruction *Op = dyn_cast<Instruction>(*i))
356 Worklist.Add(Op);
357 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000358 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000359 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000360 return 0; // Don't do anything with FI
361 }
Chris Lattner173234a2008-06-02 01:18:21 +0000362
363 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
364 APInt &KnownOne, unsigned Depth = 0) const {
365 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
366 }
367
368 bool MaskedValueIsZero(Value *V, const APInt &Mask,
369 unsigned Depth = 0) const {
370 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
371 }
372 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
373 return llvm::ComputeNumSignBits(Op, TD, Depth);
374 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000375
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000376 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000377
Reid Spencere4d87aa2006-12-23 06:05:41 +0000378 /// SimplifyCommutative - This performs a few simplifications for
379 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000380 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000381
Reid Spencere4d87aa2006-12-23 06:05:41 +0000382 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
383 /// most-complex to least-complex order.
384 bool SimplifyCompare(CmpInst &I);
385
Chris Lattner886ab6c2009-01-31 08:15:18 +0000386 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
387 /// based on the demanded bits.
388 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
389 APInt& KnownZero, APInt& KnownOne,
390 unsigned Depth);
391 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000392 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000393 unsigned Depth=0);
394
395 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
396 /// SimplifyDemandedBits knows about. See if the instruction has any
397 /// properties that allow us to simplify its operands.
398 bool SimplifyDemandedInstructionBits(Instruction &Inst);
399
Evan Cheng388df622009-02-03 10:05:09 +0000400 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
401 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000402
Chris Lattner4e998b22004-09-29 05:07:12 +0000403 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
404 // PHI node as operand #0, see if we can fold the instruction into the PHI
405 // (which is only possible if all operands to the PHI are constants).
406 Instruction *FoldOpIntoPhi(Instruction &I);
407
Chris Lattnerbac32862004-11-14 19:13:23 +0000408 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
409 // operator and they all are only used by the PHI, PHI together their
410 // inputs, and do the operation once, to the result of the PHI.
411 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000412 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000413 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
414
Chris Lattner7da52b22006-11-01 04:51:18 +0000415
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000416 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
417 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000418
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000419 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000420 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000421 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000422 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000423 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000424 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000425 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000426 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000427 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000428
Chris Lattnerafe91a52006-06-15 19:07:26 +0000429
Reid Spencerc55b2432006-12-13 18:21:21 +0000430 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000431
Dan Gohman6de29f82009-06-15 22:12:54 +0000432 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000433 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000434 unsigned GetOrEnforceKnownAlignment(Value *V,
435 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000436
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000437 };
Chris Lattner873ff012009-08-30 05:55:36 +0000438} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000439
Dan Gohman844731a2008-05-13 00:00:25 +0000440char InstCombiner::ID = 0;
441static RegisterPass<InstCombiner>
442X("instcombine", "Combine redundant instructions");
443
Chris Lattner4f98c562003-03-10 21:43:22 +0000444// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000445// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000446static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000447 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000448 if (BinaryOperator::isNeg(V) ||
449 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000450 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000451 return 3;
452 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000453 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000454 if (isa<Argument>(V)) return 3;
455 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000456}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000457
Chris Lattnerc8802d22003-03-11 00:12:48 +0000458// isOnlyUse - Return true if this instruction will be deleted if we stop using
459// it.
460static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000461 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000462}
463
Chris Lattner4cb170c2004-02-23 06:38:22 +0000464// getPromotedType - Return the specified type promoted as it would be to pass
465// though a va_arg area...
466static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000467 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
468 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000469 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000470 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000471 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000472}
473
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000474/// getBitCastOperand - If the specified operand is a CastInst, a constant
475/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
476/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000477static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000478 if (Operator *O = dyn_cast<Operator>(V)) {
479 if (O->getOpcode() == Instruction::BitCast)
480 return O->getOperand(0);
481 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
482 if (GEP->hasAllZeroIndices())
483 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000484 }
Chris Lattnereed48272005-09-13 00:40:14 +0000485 return 0;
486}
487
Reid Spencer3da59db2006-11-27 01:05:10 +0000488/// This function is a wrapper around CastInst::isEliminableCastPair. It
489/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000490static Instruction::CastOps
491isEliminableCastPair(
492 const CastInst *CI, ///< The first cast instruction
493 unsigned opcode, ///< The opcode of the second cast instruction
494 const Type *DstTy, ///< The target type for the second cast instruction
495 TargetData *TD ///< The target data for pointer size
496) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000497
Reid Spencer3da59db2006-11-27 01:05:10 +0000498 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
499 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000500
Reid Spencer3da59db2006-11-27 01:05:10 +0000501 // Get the opcodes of the two Cast instructions
502 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
503 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000504
Chris Lattnera0e69692009-03-24 18:35:40 +0000505 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000506 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000507 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000508
509 // We don't want to form an inttoptr or ptrtoint that converts to an integer
510 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000511 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000512 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000513 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000514 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000515 Res = 0;
516
517 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000518}
519
520/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
521/// in any code being generated. It does not require codegen if V is simple
522/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000523static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
524 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000525 if (V->getType() == Ty || isa<Constant>(V)) return false;
526
Chris Lattner01575b72006-05-25 23:24:33 +0000527 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000528 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000529 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000530 return false;
531 return true;
532}
533
Chris Lattner4f98c562003-03-10 21:43:22 +0000534// SimplifyCommutative - This performs a few simplifications for commutative
535// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000536//
Chris Lattner4f98c562003-03-10 21:43:22 +0000537// 1. Order operands such that they are listed from right (least complex) to
538// left (most complex). This puts constants before unary operators before
539// binary operators.
540//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
542// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000543//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000544bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000546 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000547 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000548
Chris Lattner4f98c562003-03-10 21:43:22 +0000549 if (!I.isAssociative()) return Changed;
550 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000551 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
552 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
553 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000554 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000555 cast<Constant>(I.getOperand(1)),
556 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 I.setOperand(0, Op->getOperand(0));
558 I.setOperand(1, Folded);
559 return true;
560 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
561 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
562 isOnlyUse(Op) && isOnlyUse(Op1)) {
563 Constant *C1 = cast<Constant>(Op->getOperand(1));
564 Constant *C2 = cast<Constant>(Op1->getOperand(1));
565
566 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000567 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000568 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 Op1->getOperand(0),
570 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000571 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000572 I.setOperand(0, New);
573 I.setOperand(1, Folded);
574 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000575 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000576 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000577 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000578}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000579
Reid Spencere4d87aa2006-12-23 06:05:41 +0000580/// SimplifyCompare - For a CmpInst this function just orders the operands
581/// so that theyare listed from right (least complex) to left (most complex).
582/// This puts constants before unary operators before binary operators.
583bool InstCombiner::SimplifyCompare(CmpInst &I) {
Dan Gohman14ef4f02009-08-29 23:39:38 +0000584 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000585 return false;
586 I.swapOperands();
587 // Compare instructions are not associative so there's nothing else we can do.
588 return true;
589}
590
Chris Lattner8d969642003-03-10 23:06:50 +0000591// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
592// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000593//
Dan Gohman186a6362009-08-12 16:04:34 +0000594static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000595 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000596 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000597
Chris Lattner0ce85802004-12-14 20:08:06 +0000598 // Constants can be considered to be negated values if they can be folded.
599 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000600 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000601
602 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
603 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000604 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000605
Chris Lattner8d969642003-03-10 23:06:50 +0000606 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000607}
608
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000609// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
610// instruction if the LHS is a constant negative zero (which is the 'negate'
611// form).
612//
Dan Gohman186a6362009-08-12 16:04:34 +0000613static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000614 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000615 return BinaryOperator::getFNegArgument(V);
616
617 // Constants can be considered to be negated values if they can be folded.
618 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000619 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000620
621 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
622 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000623 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000624
625 return 0;
626}
627
Dan Gohman186a6362009-08-12 16:04:34 +0000628static inline Value *dyn_castNotVal(Value *V) {
Chris Lattner8d969642003-03-10 23:06:50 +0000629 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000630 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000631
632 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000633 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000634 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000635 return 0;
636}
637
Chris Lattnerc8802d22003-03-11 00:12:48 +0000638// dyn_castFoldableMul - If this value is a multiply that can be folded into
639// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000640// non-constant operand of the multiply, and set CST to point to the multiplier.
641// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000642//
Dan Gohman186a6362009-08-12 16:04:34 +0000643static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000644 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000645 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000646 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000647 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000648 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000649 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000650 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000651 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000652 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000653 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000654 CST = ConstantInt::get(V->getType()->getContext(),
655 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000656 return I->getOperand(0);
657 }
658 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000659 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000660}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000661
Reid Spencer7177c3a2007-03-25 05:33:51 +0000662/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000663static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000664 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000665 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000666}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000667/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000668static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000669 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000670 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000671}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000672/// MultiplyOverflows - True if the multiply can not be expressed in an int
673/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000674static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000675 uint32_t W = C1->getBitWidth();
676 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
677 if (sign) {
678 LHSExt.sext(W * 2);
679 RHSExt.sext(W * 2);
680 } else {
681 LHSExt.zext(W * 2);
682 RHSExt.zext(W * 2);
683 }
684
685 APInt MulExt = LHSExt * RHSExt;
686
687 if (sign) {
688 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
689 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
690 return MulExt.slt(Min) || MulExt.sgt(Max);
691 } else
692 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
693}
Chris Lattner955f3312004-09-28 21:48:02 +0000694
Reid Spencere7816b52007-03-08 01:52:58 +0000695
Chris Lattner255d8912006-02-11 09:31:47 +0000696/// ShrinkDemandedConstant - Check to see if the specified operand of the
697/// specified instruction is a constant integer. If so, check to see if there
698/// are any bits set in the constant that are not demanded. If so, shrink the
699/// constant and return true.
700static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000701 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000702 assert(I && "No instruction?");
703 assert(OpNo < I->getNumOperands() && "Operand index too large");
704
705 // If the operand is not a constant integer, nothing to do.
706 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
707 if (!OpC) return false;
708
709 // If there are no bits set that aren't demanded, nothing to do.
710 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
711 if ((~Demanded & OpC->getValue()) == 0)
712 return false;
713
714 // This instruction is producing bits that are not demanded. Shrink the RHS.
715 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000716 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000717 return true;
718}
719
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000720// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
721// set of known zero and one bits, compute the maximum and minimum values that
722// could have the specified known zero and known one bits, returning them in
723// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000724static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000725 const APInt& KnownOne,
726 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000727 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728 KnownZero.getBitWidth() == Min.getBitWidth() &&
729 KnownZero.getBitWidth() == Max.getBitWidth() &&
730 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000731 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000732
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000733 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
734 // bit if it is unknown.
735 Min = KnownOne;
736 Max = KnownOne|UnknownBits;
737
Dan Gohman1c8491e2009-04-25 17:12:48 +0000738 if (UnknownBits.isNegative()) { // Sign bit is unknown
739 Min.set(Min.getBitWidth()-1);
740 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000741 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000742}
743
744// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
745// a set of known zero and one bits, compute the maximum and minimum values that
746// could have the specified known zero and known one bits, returning them in
747// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000748static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000749 const APInt &KnownOne,
750 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000751 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
752 KnownZero.getBitWidth() == Min.getBitWidth() &&
753 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000754 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000755 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000756
757 // The minimum value is when the unknown bits are all zeros.
758 Min = KnownOne;
759 // The maximum value is when the unknown bits are all ones.
760 Max = KnownOne|UnknownBits;
761}
Chris Lattner255d8912006-02-11 09:31:47 +0000762
Chris Lattner886ab6c2009-01-31 08:15:18 +0000763/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
764/// SimplifyDemandedBits knows about. See if the instruction has any
765/// properties that allow us to simplify its operands.
766bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000767 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000768 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
769 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
770
771 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
772 KnownZero, KnownOne, 0);
773 if (V == 0) return false;
774 if (V == &Inst) return true;
775 ReplaceInstUsesWith(Inst, V);
776 return true;
777}
778
779/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
780/// specified instruction operand if possible, updating it in place. It returns
781/// true if it made any change and false otherwise.
782bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
783 APInt &KnownZero, APInt &KnownOne,
784 unsigned Depth) {
785 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
786 KnownZero, KnownOne, Depth);
787 if (NewVal == 0) return false;
788 U.set(NewVal);
789 return true;
790}
791
792
793/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
794/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000795/// that only the bits set in DemandedMask of the result of V are ever used
796/// downstream. Consequently, depending on the mask and V, it may be possible
797/// to replace V with a constant or one of its operands. In such cases, this
798/// function does the replacement and returns true. In all other cases, it
799/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000800/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000801/// to be zero in the expression. These are provided to potentially allow the
802/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
803/// the expression. KnownOne and KnownZero always follow the invariant that
804/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
805/// the bits in KnownOne and KnownZero may only be accurate for those bits set
806/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
807/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000808///
809/// This returns null if it did not change anything and it permits no
810/// simplification. This returns V itself if it did some simplification of V's
811/// operands based on the information about what bits are demanded. This returns
812/// some other non-null value if it found out that V is equal to another value
813/// in the context where the specified bits are demanded, but not for all users.
814Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
815 APInt &KnownZero, APInt &KnownOne,
816 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000817 assert(V != 0 && "Null pointer of Value???");
818 assert(Depth <= 6 && "Limit Search Depth");
819 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000820 const Type *VTy = V->getType();
821 assert((TD || !isa<PointerType>(VTy)) &&
822 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000823 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
824 (!VTy->isIntOrIntVector() ||
825 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000826 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000827 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000828 "Value *V, DemandedMask, KnownZero and KnownOne "
829 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000830 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
831 // We know all of the bits for a constant!
832 KnownOne = CI->getValue() & DemandedMask;
833 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000834 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000835 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000836 if (isa<ConstantPointerNull>(V)) {
837 // We know all of the bits for a constant!
838 KnownOne.clear();
839 KnownZero = DemandedMask;
840 return 0;
841 }
842
Chris Lattner08d2cc72009-01-31 07:26:06 +0000843 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000844 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000845 if (DemandedMask == 0) { // Not demanding any bits from V.
846 if (isa<UndefValue>(V))
847 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000848 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000849 }
850
Chris Lattner4598c942009-01-31 08:24:16 +0000851 if (Depth == 6) // Limit search depth.
852 return 0;
853
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000854 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
855 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
856
Dan Gohman1c8491e2009-04-25 17:12:48 +0000857 Instruction *I = dyn_cast<Instruction>(V);
858 if (!I) {
859 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
860 return 0; // Only analyze instructions.
861 }
862
Chris Lattner4598c942009-01-31 08:24:16 +0000863 // If there are multiple uses of this value and we aren't at the root, then
864 // we can't do any simplifications of the operands, because DemandedMask
865 // only reflects the bits demanded by *one* of the users.
866 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000867 // Despite the fact that we can't simplify this instruction in all User's
868 // context, we can at least compute the knownzero/knownone bits, and we can
869 // do simplifications that apply to *just* the one user if we know that
870 // this instruction has a simpler value in that context.
871 if (I->getOpcode() == Instruction::And) {
872 // If either the LHS or the RHS are Zero, the result is zero.
873 ComputeMaskedBits(I->getOperand(1), DemandedMask,
874 RHSKnownZero, RHSKnownOne, Depth+1);
875 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
876 LHSKnownZero, LHSKnownOne, Depth+1);
877
878 // If all of the demanded bits are known 1 on one side, return the other.
879 // These bits cannot contribute to the result of the 'and' in this
880 // context.
881 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
882 (DemandedMask & ~LHSKnownZero))
883 return I->getOperand(0);
884 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
885 (DemandedMask & ~RHSKnownZero))
886 return I->getOperand(1);
887
888 // If all of the demanded bits in the inputs are known zeros, return zero.
889 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000890 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000891
892 } else if (I->getOpcode() == Instruction::Or) {
893 // We can simplify (X|Y) -> X or Y in the user's context if we know that
894 // only bits from X or Y are demanded.
895
896 // If either the LHS or the RHS are One, the result is One.
897 ComputeMaskedBits(I->getOperand(1), DemandedMask,
898 RHSKnownZero, RHSKnownOne, Depth+1);
899 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
900 LHSKnownZero, LHSKnownOne, Depth+1);
901
902 // If all of the demanded bits are known zero on one side, return the
903 // other. These bits cannot contribute to the result of the 'or' in this
904 // context.
905 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
906 (DemandedMask & ~LHSKnownOne))
907 return I->getOperand(0);
908 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
909 (DemandedMask & ~RHSKnownOne))
910 return I->getOperand(1);
911
912 // If all of the potentially set bits on one side are known to be set on
913 // the other side, just use the 'other' side.
914 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
915 (DemandedMask & (~RHSKnownZero)))
916 return I->getOperand(0);
917 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
918 (DemandedMask & (~LHSKnownZero)))
919 return I->getOperand(1);
920 }
921
Chris Lattner4598c942009-01-31 08:24:16 +0000922 // Compute the KnownZero/KnownOne bits to simplify things downstream.
923 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
924 return 0;
925 }
926
927 // If this is the root being simplified, allow it to have multiple uses,
928 // just set the DemandedMask to all bits so that we can try to simplify the
929 // operands. This allows visitTruncInst (for example) to simplify the
930 // operand of a trunc without duplicating all the logic below.
931 if (Depth == 0 && !V->hasOneUse())
932 DemandedMask = APInt::getAllOnesValue(BitWidth);
933
Reid Spencer8cb68342007-03-12 17:25:59 +0000934 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000935 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000936 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000937 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000938 case Instruction::And:
939 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000940 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941 RHSKnownZero, RHSKnownOne, Depth+1) ||
942 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000943 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000944 return I;
945 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
946 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000947
948 // If all of the demanded bits are known 1 on one side, return the other.
949 // These bits cannot contribute to the result of the 'and'.
950 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
951 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000952 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000953 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
954 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000955 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000956
957 // If all of the demanded bits in the inputs are known zeros, return zero.
958 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000959 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000960
961 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000962 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000963 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000964
965 // Output known-1 bits are only known if set in both the LHS & RHS.
966 RHSKnownOne &= LHSKnownOne;
967 // Output known-0 are known to be clear if zero in either the LHS | RHS.
968 RHSKnownZero |= LHSKnownZero;
969 break;
970 case Instruction::Or:
971 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000972 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
973 RHSKnownZero, RHSKnownOne, Depth+1) ||
974 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +0000975 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000976 return I;
977 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
978 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000979
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'or'.
982 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
983 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000984 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000985 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
986 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000987 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000988
989 // If all of the potentially set bits on one side are known to be set on
990 // the other side, just use the 'other' side.
991 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
992 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000993 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000994 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
995 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000996 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000997
998 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000999 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001000 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001001
1002 // Output known-0 bits are only known if clear in both the LHS & RHS.
1003 RHSKnownZero &= LHSKnownZero;
1004 // Output known-1 are known to be set if set in either the LHS | RHS.
1005 RHSKnownOne |= LHSKnownOne;
1006 break;
1007 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001008 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1) ||
1010 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001011 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001012 return I;
1013 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1014 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001015
1016 // If all of the demanded bits are known zero on one side, return the other.
1017 // These bits cannot contribute to the result of the 'xor'.
1018 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001019 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001020 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022
1023 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1024 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1025 (RHSKnownOne & LHSKnownOne);
1026 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1027 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1028 (RHSKnownOne & LHSKnownZero);
1029
1030 // If all of the demanded bits are known to be zero on one side or the
1031 // other, turn this into an *inclusive* or.
1032 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner74381062009-08-30 07:44:24 +00001033 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0)
1034 return Builder->CreateOr(I->getOperand(0), I->getOperand(1),I->getName());
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 // If all of the demanded bits on one side are known, and all of the set
1037 // bits on that side are also known to be set on the other side, turn this
1038 // into an AND, as we know the bits will be cleared.
1039 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1040 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1041 // all known
1042 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001043 Constant *AndC = Constant::getIntegerValue(VTy,
1044 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001045 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001046 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001047 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001048 }
1049 }
1050
1051 // If the RHS is a constant, see if we can simplify it.
1052 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001053 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001054 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001055
1056 RHSKnownZero = KnownZeroOut;
1057 RHSKnownOne = KnownOneOut;
1058 break;
1059 }
1060 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001061 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1062 RHSKnownZero, RHSKnownOne, Depth+1) ||
1063 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001064 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001065 return I;
1066 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1067 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001068
1069 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001070 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1071 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001072 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001073
1074 // Only known if known in both the LHS and RHS.
1075 RHSKnownOne &= LHSKnownOne;
1076 RHSKnownZero &= LHSKnownZero;
1077 break;
1078 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001079 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001080 DemandedMask.zext(truncBf);
1081 RHSKnownZero.zext(truncBf);
1082 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001083 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001084 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 DemandedMask.trunc(BitWidth);
1087 RHSKnownZero.trunc(BitWidth);
1088 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001089 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001090 break;
1091 }
1092 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001093 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001094 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001095
1096 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1097 if (const VectorType *SrcVTy =
1098 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1099 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1100 // Don't touch a bitcast between vectors of different element counts.
1101 return false;
1102 } else
1103 // Don't touch a scalar-to-vector bitcast.
1104 return false;
1105 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1106 // Don't touch a vector-to-scalar bitcast.
1107 return false;
1108
Chris Lattner886ab6c2009-01-31 08:15:18 +00001109 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001110 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001111 return I;
1112 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001113 break;
1114 case Instruction::ZExt: {
1115 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001116 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001117
Zhou Shengd48653a2007-03-29 04:45:55 +00001118 DemandedMask.trunc(SrcBitWidth);
1119 RHSKnownZero.trunc(SrcBitWidth);
1120 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001121 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001122 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001123 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001124 DemandedMask.zext(BitWidth);
1125 RHSKnownZero.zext(BitWidth);
1126 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001127 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001128 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001129 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001130 break;
1131 }
1132 case Instruction::SExt: {
1133 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001134 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001135
Reid Spencer8cb68342007-03-12 17:25:59 +00001136 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001137 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
Zhou Sheng01542f32007-03-29 02:26:30 +00001139 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001140 // If any of the sign extended bits are demanded, we know that the sign
1141 // bit is demanded.
1142 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001143 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001144
Zhou Shengd48653a2007-03-29 04:45:55 +00001145 InputDemandedBits.trunc(SrcBitWidth);
1146 RHSKnownZero.trunc(SrcBitWidth);
1147 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001149 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 InputDemandedBits.zext(BitWidth);
1152 RHSKnownZero.zext(BitWidth);
1153 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001155
1156 // If the sign bit of the input is known set or clear, then we know the
1157 // top bits of the result.
1158
1159 // If the input sign bit is known zero, or if the NewBits are not demanded
1160 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001161 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001162 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001163 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1164 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001165 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001166 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001167 }
1168 break;
1169 }
1170 case Instruction::Add: {
1171 // Figure out what the input bits are. If the top bits of the and result
1172 // are not demanded, then the add doesn't demand them from its input
1173 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001175
1176 // If there is a constant on the RHS, there are a variety of xformations
1177 // we can do.
1178 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179 // If null, this should be simplified elsewhere. Some of the xforms here
1180 // won't work if the RHS is zero.
1181 if (RHS->isZero())
1182 break;
1183
1184 // If the top bit of the output is demanded, demand everything from the
1185 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001186 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001187
1188 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001189 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001190 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001191 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001192
1193 // If the RHS of the add has bits set that can't affect the input, reduce
1194 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001195 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001196 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001197
1198 // Avoid excess work.
1199 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1200 break;
1201
1202 // Turn it into OR if input bits are zero.
1203 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1204 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001205 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001206 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001207 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001208 }
1209
1210 // We can say something about the output known-zero and known-one bits,
1211 // depending on potential carries from the input constant and the
1212 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1213 // bits set and the RHS constant is 0x01001, then we know we have a known
1214 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1215
1216 // To compute this, we first compute the potential carry bits. These are
1217 // the bits which may be modified. I'm not aware of a better way to do
1218 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001220 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001221
1222 // Now that we know which bits have carries, compute the known-1/0 sets.
1223
1224 // Bits are known one if they are known zero in one operand and one in the
1225 // other, and there is no input carry.
1226 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1227 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1228
1229 // Bits are known zero if they are known zero in both operands and there
1230 // is no input carry.
1231 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1232 } else {
1233 // If the high-bits of this ADD are not demanded, then it does not demand
1234 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001235 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001236 // Right fill the mask of bits for this ADD to demand the most
1237 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001238 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1240 LHSKnownZero, LHSKnownOne, Depth+1) ||
1241 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001242 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001243 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001244 }
1245 }
1246 break;
1247 }
1248 case Instruction::Sub:
1249 // If the high-bits of this SUB are not demanded, then it does not demand
1250 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001251 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001252 // Right fill the mask of bits for this SUB to demand the most
1253 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001254 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001255 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1257 LHSKnownZero, LHSKnownOne, Depth+1) ||
1258 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001259 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001260 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001261 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001262 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1263 // the known zeros and ones.
1264 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001265 break;
1266 case Instruction::Shl:
1267 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001268 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001269 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001270 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 return I;
1273 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001274 RHSKnownZero <<= ShiftAmt;
1275 RHSKnownOne <<= ShiftAmt;
1276 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001277 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001278 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001279 }
1280 break;
1281 case Instruction::LShr:
1282 // For a logical shift right
1283 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001284 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001285
Reid Spencer8cb68342007-03-12 17:25:59 +00001286 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001287 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001288 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001289 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001290 return I;
1291 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001292 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1293 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001294 if (ShiftAmt) {
1295 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001296 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001297 RHSKnownZero |= HighBits; // high bits known zero.
1298 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001299 }
1300 break;
1301 case Instruction::AShr:
1302 // If this is an arithmetic shift right and only the low-bit is set, we can
1303 // always convert this into a logical shr, even if the shift amount is
1304 // variable. The low bit of the shift cannot be an input sign bit unless
1305 // the shift amount is >= the size of the datatype, which is undefined.
1306 if (DemandedMask == 1) {
1307 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001310 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001311 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001312
1313 // If the sign bit is the only bit demanded by this ashr, then there is no
1314 // need to do it, the shift doesn't change the high bit.
1315 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001316 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001317
1318 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001319 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001320
Reid Spencer8cb68342007-03-12 17:25:59 +00001321 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001322 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001323 // If any of the "high bits" are demanded, we should set the sign bit as
1324 // demanded.
1325 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1326 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001327 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001328 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001329 return I;
1330 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001331 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001332 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001333 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1334 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1335
1336 // Handle the sign bits.
1337 APInt SignBit(APInt::getSignBit(BitWidth));
1338 // Adjust to where it is now in the mask.
1339 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1340
1341 // If the input sign bit is known to be zero, or if none of the top bits
1342 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001343 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 (HighBits & ~DemandedMask) == HighBits) {
1345 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001346 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001347 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001348 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001349 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1350 RHSKnownOne |= HighBits;
1351 }
1352 }
1353 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001354 case Instruction::SRem:
1355 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001356 APInt RA = Rem->getValue().abs();
1357 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001358 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001359 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001360
Nick Lewycky8e394322008-11-02 02:41:50 +00001361 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001362 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001363 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001364 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001365 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001366
1367 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1368 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001369
1370 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001371
Chris Lattner886ab6c2009-01-31 08:15:18 +00001372 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001373 }
1374 }
1375 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001376 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001377 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1378 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001379 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1380 KnownZero2, KnownOne2, Depth+1) ||
1381 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001382 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001383 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001384
Chris Lattner455e9ab2009-01-21 18:09:24 +00001385 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001386 Leaders = std::max(Leaders,
1387 KnownZero2.countLeadingOnes());
1388 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001389 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001390 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001391 case Instruction::Call:
1392 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1393 switch (II->getIntrinsicID()) {
1394 default: break;
1395 case Intrinsic::bswap: {
1396 // If the only bits demanded come from one byte of the bswap result,
1397 // just shift the input byte into position to eliminate the bswap.
1398 unsigned NLZ = DemandedMask.countLeadingZeros();
1399 unsigned NTZ = DemandedMask.countTrailingZeros();
1400
1401 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1402 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1403 // have 14 leading zeros, round to 8.
1404 NLZ &= ~7;
1405 NTZ &= ~7;
1406 // If we need exactly one byte, we can do this transformation.
1407 if (BitWidth-NLZ-NTZ == 8) {
1408 unsigned ResultBit = NTZ;
1409 unsigned InputBit = BitWidth-NTZ-8;
1410
1411 // Replace this with either a left or right shift to get the byte into
1412 // the right place.
1413 Instruction *NewVal;
1414 if (InputBit > ResultBit)
1415 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001416 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001417 else
1418 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001419 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001420 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001421 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001422 }
1423
1424 // TODO: Could compute known zero/one bits based on the input.
1425 break;
1426 }
1427 }
1428 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001429 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001430 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001431 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001432
1433 // If the client is only demanding bits that we know, return the known
1434 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001435 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1436 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001437 return false;
1438}
1439
Chris Lattner867b99f2006-10-05 06:55:50 +00001440
Mon P Wangaeb06d22008-11-10 04:46:22 +00001441/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001442/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001443/// actually used by the caller. This method analyzes which elements of the
1444/// operand are undef and returns that information in UndefElts.
1445///
1446/// If the information about demanded elements can be used to simplify the
1447/// operation, the operation is simplified, then the resultant value is
1448/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001449Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1450 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001451 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001452 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001453 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001454 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001455
1456 if (isa<UndefValue>(V)) {
1457 // If the entire vector is undefined, just return this info.
1458 UndefElts = EltMask;
1459 return 0;
1460 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1461 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001462 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001463 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001464
Chris Lattner867b99f2006-10-05 06:55:50 +00001465 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001466 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1467 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001468 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001469
1470 std::vector<Constant*> Elts;
1471 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001472 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001473 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001474 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001475 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1476 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001477 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001478 } else { // Otherwise, defined.
1479 Elts.push_back(CP->getOperand(i));
1480 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001481
Chris Lattner867b99f2006-10-05 06:55:50 +00001482 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001483 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001484 return NewCP != CP ? NewCP : 0;
1485 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001486 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001487 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001488
1489 // Check if this is identity. If so, return 0 since we are not simplifying
1490 // anything.
1491 if (DemandedElts == ((1ULL << VWidth) -1))
1492 return 0;
1493
Reid Spencer9d6565a2007-02-15 02:26:10 +00001494 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001495 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001496 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001497 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001498 for (unsigned i = 0; i != VWidth; ++i) {
1499 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1500 Elts.push_back(Elt);
1501 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001502 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001503 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001504 }
1505
Dan Gohman488fbfc2008-09-09 18:11:14 +00001506 // Limit search depth.
1507 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001508 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001509
1510 // If multiple users are using the root value, procede with
1511 // simplification conservatively assuming that all elements
1512 // are needed.
1513 if (!V->hasOneUse()) {
1514 // Quit if we find multiple users of a non-root value though.
1515 // They'll be handled when it's their turn to be visited by
1516 // the main instcombine process.
1517 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001518 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001519 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001520
1521 // Conservatively assume that all elements are needed.
1522 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001523 }
1524
1525 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001526 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001527
1528 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001529 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 Value *TmpV;
1531 switch (I->getOpcode()) {
1532 default: break;
1533
1534 case Instruction::InsertElement: {
1535 // If this is a variable index, we don't know which element it overwrites.
1536 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001537 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 if (Idx == 0) {
1539 // Note that we can't propagate undef elt info, because we don't know
1540 // which elt is getting updated.
1541 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1542 UndefElts2, Depth+1);
1543 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1544 break;
1545 }
1546
1547 // If this is inserting an element that isn't demanded, remove this
1548 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001549 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001550 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1551 Worklist.Add(I);
1552 return I->getOperand(0);
1553 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001554
1555 // Otherwise, the element inserted overwrites whatever was there, so the
1556 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001557 APInt DemandedElts2 = DemandedElts;
1558 DemandedElts2.clear(IdxNo);
1559 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001560 UndefElts, Depth+1);
1561 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1562
1563 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001564 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001565 break;
1566 }
1567 case Instruction::ShuffleVector: {
1568 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001569 uint64_t LHSVWidth =
1570 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001571 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001572 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001573 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574 unsigned MaskVal = Shuffle->getMaskValue(i);
1575 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001576 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001577 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001578 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001579 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001580 else
Evan Cheng388df622009-02-03 10:05:09 +00001581 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001582 }
1583 }
1584 }
1585
Nate Begeman7b254672009-02-11 22:36:25 +00001586 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001587 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001588 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001589 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1590
Nate Begeman7b254672009-02-11 22:36:25 +00001591 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001592 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1593 UndefElts3, Depth+1);
1594 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1595
1596 bool NewUndefElts = false;
1597 for (unsigned i = 0; i < VWidth; i++) {
1598 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001599 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001600 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001601 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001602 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001603 NewUndefElts = true;
1604 UndefElts.set(i);
1605 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001606 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001607 if (UndefElts3[MaskVal - LHSVWidth]) {
1608 NewUndefElts = true;
1609 UndefElts.set(i);
1610 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001611 }
1612 }
1613
1614 if (NewUndefElts) {
1615 // Add additional discovered undefs.
1616 std::vector<Constant*> Elts;
1617 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001618 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001619 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001620 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001621 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001622 Shuffle->getMaskValue(i)));
1623 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001624 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001625 MadeChange = true;
1626 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001627 break;
1628 }
Chris Lattner69878332007-04-14 22:29:23 +00001629 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001630 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001631 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1632 if (!VTy) break;
1633 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001634 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001635 unsigned Ratio;
1636
1637 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001638 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001639 // elements as are demanded of us.
1640 Ratio = 1;
1641 InputDemandedElts = DemandedElts;
1642 } else if (VWidth > InVWidth) {
1643 // Untested so far.
1644 break;
1645
1646 // If there are more elements in the result than there are in the source,
1647 // then an input element is live if any of the corresponding output
1648 // elements are live.
1649 Ratio = VWidth/InVWidth;
1650 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001651 if (DemandedElts[OutIdx])
1652 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001653 }
1654 } else {
1655 // Untested so far.
1656 break;
1657
1658 // If there are more elements in the source than there are in the result,
1659 // then an input element is live if the corresponding output element is
1660 // live.
1661 Ratio = InVWidth/VWidth;
1662 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001663 if (DemandedElts[InIdx/Ratio])
1664 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001665 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001666
Chris Lattner69878332007-04-14 22:29:23 +00001667 // div/rem demand all inputs, because they don't want divide by zero.
1668 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1669 UndefElts2, Depth+1);
1670 if (TmpV) {
1671 I->setOperand(0, TmpV);
1672 MadeChange = true;
1673 }
1674
1675 UndefElts = UndefElts2;
1676 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001677 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001678 // If there are more elements in the result than there are in the source,
1679 // then an output element is undef if the corresponding input element is
1680 // undef.
1681 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001682 if (UndefElts2[OutIdx/Ratio])
1683 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001684 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001685 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001686 // If there are more elements in the source than there are in the result,
1687 // then a result element is undef if all of the corresponding input
1688 // elements are undef.
1689 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1690 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001691 if (!UndefElts2[InIdx]) // Not undef?
1692 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001693 }
1694 break;
1695 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001696 case Instruction::And:
1697 case Instruction::Or:
1698 case Instruction::Xor:
1699 case Instruction::Add:
1700 case Instruction::Sub:
1701 case Instruction::Mul:
1702 // div/rem demand all inputs, because they don't want divide by zero.
1703 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1704 UndefElts, Depth+1);
1705 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1706 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1707 UndefElts2, Depth+1);
1708 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1709
1710 // Output elements are undefined if both are undefined. Consider things
1711 // like undef&0. The result is known zero, not undef.
1712 UndefElts &= UndefElts2;
1713 break;
1714
1715 case Instruction::Call: {
1716 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1717 if (!II) break;
1718 switch (II->getIntrinsicID()) {
1719 default: break;
1720
1721 // Binary vector operations that work column-wise. A dest element is a
1722 // function of the corresponding input elements from the two inputs.
1723 case Intrinsic::x86_sse_sub_ss:
1724 case Intrinsic::x86_sse_mul_ss:
1725 case Intrinsic::x86_sse_min_ss:
1726 case Intrinsic::x86_sse_max_ss:
1727 case Intrinsic::x86_sse2_sub_sd:
1728 case Intrinsic::x86_sse2_mul_sd:
1729 case Intrinsic::x86_sse2_min_sd:
1730 case Intrinsic::x86_sse2_max_sd:
1731 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1732 UndefElts, Depth+1);
1733 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1734 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1735 UndefElts2, Depth+1);
1736 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1737
1738 // If only the low elt is demanded and this is a scalarizable intrinsic,
1739 // scalarize it now.
1740 if (DemandedElts == 1) {
1741 switch (II->getIntrinsicID()) {
1742 default: break;
1743 case Intrinsic::x86_sse_sub_ss:
1744 case Intrinsic::x86_sse_mul_ss:
1745 case Intrinsic::x86_sse2_sub_sd:
1746 case Intrinsic::x86_sse2_mul_sd:
1747 // TODO: Lower MIN/MAX/ABS/etc
1748 Value *LHS = II->getOperand(1);
1749 Value *RHS = II->getOperand(2);
1750 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001751 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001752 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001753 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001754 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001755
1756 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001757 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001758 case Intrinsic::x86_sse_sub_ss:
1759 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001760 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001761 II->getName()), *II);
1762 break;
1763 case Intrinsic::x86_sse_mul_ss:
1764 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001765 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001766 II->getName()), *II);
1767 break;
1768 }
1769
1770 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001771 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001772 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001773 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001774 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001775 return New;
1776 }
1777 }
1778
1779 // Output elements are undefined if both are undefined. Consider things
1780 // like undef&0. The result is known zero, not undef.
1781 UndefElts &= UndefElts2;
1782 break;
1783 }
1784 break;
1785 }
1786 }
1787 return MadeChange ? I : 0;
1788}
1789
Dan Gohman45b4e482008-05-19 22:14:15 +00001790
Chris Lattner564a7272003-08-13 19:01:45 +00001791/// AssociativeOpt - Perform an optimization on an associative operator. This
1792/// function is designed to check a chain of associative operators for a
1793/// potential to apply a certain optimization. Since the optimization may be
1794/// applicable if the expression was reassociated, this checks the chain, then
1795/// reassociates the expression as necessary to expose the optimization
1796/// opportunity. This makes use of a special Functor, which must define
1797/// 'shouldApply' and 'apply' methods.
1798///
1799template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001800static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001801 unsigned Opcode = Root.getOpcode();
1802 Value *LHS = Root.getOperand(0);
1803
1804 // Quick check, see if the immediate LHS matches...
1805 if (F.shouldApply(LHS))
1806 return F.apply(Root);
1807
1808 // Otherwise, if the LHS is not of the same opcode as the root, return.
1809 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001810 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001811 // Should we apply this transform to the RHS?
1812 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1813
1814 // If not to the RHS, check to see if we should apply to the LHS...
1815 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1816 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1817 ShouldApply = true;
1818 }
1819
1820 // If the functor wants to apply the optimization to the RHS of LHSI,
1821 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1822 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001823 // Now all of the instructions are in the current basic block, go ahead
1824 // and perform the reassociation.
1825 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1826
1827 // First move the selected RHS to the LHS of the root...
1828 Root.setOperand(0, LHSI->getOperand(1));
1829
1830 // Make what used to be the LHS of the root be the user of the root...
1831 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001832 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001833 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001834 return 0;
1835 }
Chris Lattner65725312004-04-16 18:08:07 +00001836 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001837 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001838 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001839 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001840 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001841
1842 // Now propagate the ExtraOperand down the chain of instructions until we
1843 // get to LHSI.
1844 while (TmpLHSI != LHSI) {
1845 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001846 // Move the instruction to immediately before the chain we are
1847 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001848 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001849 ARI = NextLHSI;
1850
Chris Lattner564a7272003-08-13 19:01:45 +00001851 Value *NextOp = NextLHSI->getOperand(1);
1852 NextLHSI->setOperand(1, ExtraOperand);
1853 TmpLHSI = NextLHSI;
1854 ExtraOperand = NextOp;
1855 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001856
Chris Lattner564a7272003-08-13 19:01:45 +00001857 // Now that the instructions are reassociated, have the functor perform
1858 // the transformation...
1859 return F.apply(Root);
1860 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001861
Chris Lattner564a7272003-08-13 19:01:45 +00001862 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1863 }
1864 return 0;
1865}
1866
Dan Gohman844731a2008-05-13 00:00:25 +00001867namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001868
Nick Lewycky02d639f2008-05-23 04:34:58 +00001869// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001870struct AddRHS {
1871 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001872 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001873 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1874 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001875 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001876 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001877 }
1878};
1879
1880// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1881// iff C1&C2 == 0
1882struct AddMaskingAnd {
1883 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001884 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001885 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001886 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001887 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001888 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001889 }
1890 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001891 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001892 }
1893};
1894
Dan Gohman844731a2008-05-13 00:00:25 +00001895}
1896
Chris Lattner6e7ba452005-01-01 16:22:27 +00001897static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001898 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001899 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00001900 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001901 }
1902
Chris Lattner2eefe512004-04-09 19:05:30 +00001903 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001904 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1905 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001906
Chris Lattner2eefe512004-04-09 19:05:30 +00001907 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1908 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001909 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1910 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001911 }
1912
1913 Value *Op0 = SO, *Op1 = ConstOperand;
1914 if (!ConstIsRHS)
1915 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001916
Chris Lattner6e7ba452005-01-01 16:22:27 +00001917 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001918 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1919 SO->getName()+".op");
1920 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1921 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1922 SO->getName()+".cmp");
1923 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1924 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1925 SO->getName()+".cmp");
1926 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001927}
1928
1929// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1930// constant as the other operand, try to fold the binary operator into the
1931// select arguments. This also works for Cast instructions, which obviously do
1932// not have a second operand.
1933static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1934 InstCombiner *IC) {
1935 // Don't modify shared select instructions
1936 if (!SI->hasOneUse()) return 0;
1937 Value *TV = SI->getOperand(1);
1938 Value *FV = SI->getOperand(2);
1939
1940 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001941 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00001942 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001943
Chris Lattner6e7ba452005-01-01 16:22:27 +00001944 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1945 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1946
Gabor Greif051a9502008-04-06 20:25:17 +00001947 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1948 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001949 }
1950 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001951}
1952
Chris Lattner4e998b22004-09-29 05:07:12 +00001953
1954/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1955/// node as operand #0, see if we can fold the instruction into the PHI (which
1956/// is only possible if all operands to the PHI are constants).
1957Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1958 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001959 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001960 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001961
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001962 // Check to see if all of the operands of the PHI are constants. If there is
1963 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001964 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001965 BasicBlock *NonConstBB = 0;
1966 for (unsigned i = 0; i != NumPHIValues; ++i)
1967 if (!isa<Constant>(PN->getIncomingValue(i))) {
1968 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001969 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001970 NonConstBB = PN->getIncomingBlock(i);
1971
1972 // If the incoming non-constant value is in I's block, we have an infinite
1973 // loop.
1974 if (NonConstBB == I.getParent())
1975 return 0;
1976 }
1977
1978 // If there is exactly one non-constant value, we can insert a copy of the
1979 // operation in that block. However, if this is a critical edge, we would be
1980 // inserting the computation one some other paths (e.g. inside a loop). Only
1981 // do this if the pred block is unconditionally branching into the phi block.
1982 if (NonConstBB) {
1983 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1984 if (!BI || !BI->isUnconditional()) return 0;
1985 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001986
1987 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00001988 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001989 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001990 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001991 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001992
1993 // Next, add all of the operands to the PHI.
1994 if (I.getNumOperands() == 2) {
1995 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001996 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001997 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001998 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001999 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002000 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002001 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002002 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002003 } else {
2004 assert(PN->getIncomingBlock(i) == NonConstBB);
2005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002006 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002007 PN->getIncomingValue(i), C, "phitmp",
2008 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002009 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002010 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002011 CI->getPredicate(),
2012 PN->getIncomingValue(i), C, "phitmp",
2013 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002014 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002015 llvm_unreachable("Unknown binop!");
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002016
Chris Lattner7a1e9242009-08-30 06:13:40 +00002017 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002018 }
2019 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002020 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002021 } else {
2022 CastInst *CI = cast<CastInst>(&I);
2023 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002024 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002025 Value *InV;
2026 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002027 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002028 } else {
2029 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002030 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002031 I.getType(), "phitmp",
2032 NonConstBB->getTerminator());
Chris Lattner7a1e9242009-08-30 06:13:40 +00002033 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002034 }
2035 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002036 }
2037 }
2038 return ReplaceInstUsesWith(I, NewPN);
2039}
2040
Chris Lattner2454a2e2008-01-29 06:52:45 +00002041
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002042/// WillNotOverflowSignedAdd - Return true if we can prove that:
2043/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2044/// This basically requires proving that the add in the original type would not
2045/// overflow to change the sign bit or have a carry out.
2046bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2047 // There are different heuristics we can use for this. Here are some simple
2048 // ones.
2049
2050 // Add has the property that adding any two 2's complement numbers can only
2051 // have one carry bit which can change a sign. As such, if LHS and RHS each
2052 // have at least two sign bits, we know that the addition of the two values will
2053 // sign extend fine.
2054 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2055 return true;
2056
2057
2058 // If one of the operands only has one non-zero bit, and if the other operand
2059 // has a known-zero bit in a more significant place than it (not including the
2060 // sign bit) the ripple may go up to and fill the zero, but won't change the
2061 // sign. For example, (X & ~4) + 1.
2062
2063 // TODO: Implement.
2064
2065 return false;
2066}
2067
Chris Lattner2454a2e2008-01-29 06:52:45 +00002068
Chris Lattner7e708292002-06-25 16:13:24 +00002069Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002070 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002071 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002072
Chris Lattner66331a42004-04-10 22:01:55 +00002073 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002074 // X + undef -> undef
2075 if (isa<UndefValue>(RHS))
2076 return ReplaceInstUsesWith(I, RHS);
2077
Chris Lattner66331a42004-04-10 22:01:55 +00002078 // X + 0 --> X
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002079 if (RHSC->isNullValue())
2080 return ReplaceInstUsesWith(I, LHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00002081
Chris Lattner66331a42004-04-10 22:01:55 +00002082 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002083 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002084 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002085 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002086 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002087 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002088
2089 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2090 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002091 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002092 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002093
Eli Friedman709b33d2009-07-13 22:27:52 +00002094 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002095 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002096 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002097 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002098 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002099
2100 if (isa<PHINode>(LHS))
2101 if (Instruction *NV = FoldOpIntoPhi(I))
2102 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002103
Chris Lattner4f637d42006-01-06 17:59:59 +00002104 ConstantInt *XorRHS = 0;
2105 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002106 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002107 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002108 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002109 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002110
Zhou Sheng4351c642007-04-02 08:20:41 +00002111 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002112 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2113 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002114 do {
2115 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002116 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2117 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002118 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2119 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002120 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002121 if (!MaskedValueIsZero(XorLHS,
2122 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002123 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002124 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002125 }
2126 }
2127 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002128 C0080Val = APIntOps::lshr(C0080Val, Size);
2129 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2130 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002131
Reid Spencer35c38852007-03-28 01:36:16 +00002132 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002133 // with funny bit widths then this switch statement should be removed. It
2134 // is just here to get the size of the "middle" type back up to something
2135 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002136 const Type *MiddleType = 0;
2137 switch (Size) {
2138 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002139 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2140 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2141 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002142 }
2143 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002144 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002145 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002146 }
2147 }
Chris Lattner66331a42004-04-10 22:01:55 +00002148 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002149
Owen Anderson1d0be152009-08-13 21:58:54 +00002150 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002151 return BinaryOperator::CreateXor(LHS, RHS);
2152
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002153 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002154 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002155 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002156 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002157
2158 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2159 if (RHSI->getOpcode() == Instruction::Sub)
2160 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2161 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2162 }
2163 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2164 if (LHSI->getOpcode() == Instruction::Sub)
2165 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2166 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2167 }
Robert Bocchino71698282004-07-27 21:02:21 +00002168 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002169
Chris Lattner5c4afb92002-05-08 22:46:53 +00002170 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002171 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002172 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002173 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002174 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002175 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002176 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002177 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002178 }
2179
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002180 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002181 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002182
2183 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002184 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002185 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002186 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002187
Misha Brukmanfd939082005-04-21 23:48:37 +00002188
Chris Lattner50af16a2004-11-13 19:50:12 +00002189 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002190 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002191 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002192 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002193
2194 // X*C1 + X*C2 --> X * (C1+C2)
2195 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002196 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002197 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002198 }
2199
2200 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002201 if (dyn_castFoldableMul(RHS, C2) == LHS)
2202 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002203
Chris Lattnere617c9e2007-01-05 02:17:46 +00002204 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002205 if (dyn_castNotVal(LHS) == RHS ||
2206 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002207 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002208
Chris Lattnerad3448c2003-02-18 19:57:07 +00002209
Chris Lattner564a7272003-08-13 19:01:45 +00002210 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002211 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2212 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002213 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002214
2215 // A+B --> A|B iff A and B have no bits set in common.
2216 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2217 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2218 APInt LHSKnownOne(IT->getBitWidth(), 0);
2219 APInt LHSKnownZero(IT->getBitWidth(), 0);
2220 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2221 if (LHSKnownZero != 0) {
2222 APInt RHSKnownOne(IT->getBitWidth(), 0);
2223 APInt RHSKnownZero(IT->getBitWidth(), 0);
2224 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2225
2226 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002227 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002228 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002229 }
2230 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002231
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002232 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002233 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002234 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002235 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2236 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002237 if (W != Y) {
2238 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002239 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002240 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002241 std::swap(W, X);
2242 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002243 std::swap(Y, Z);
2244 std::swap(W, X);
2245 }
2246 }
2247
2248 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002249 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002250 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002251 }
2252 }
2253 }
2254
Chris Lattner6b032052003-10-02 15:11:26 +00002255 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002256 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002257 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002258 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002259
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002260 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002261 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002262 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002263 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002264 if (Anded == CRHS) {
2265 // See if all bits from the first bit set in the Add RHS up are included
2266 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002267 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002268
2269 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002270 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002271
2272 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002273 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002274
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002275 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2276 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002277 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002278 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002279 }
2280 }
2281 }
2282
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002283 // Try to fold constant add into select arguments.
2284 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002285 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002286 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002287 }
2288
Chris Lattner42790482007-12-20 01:56:58 +00002289 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002290 {
2291 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002292 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002293 if (!SI) {
2294 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002295 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002296 }
Chris Lattner42790482007-12-20 01:56:58 +00002297 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002298 Value *TV = SI->getTrueValue();
2299 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002300 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002301
2302 // Can we fold the add into the argument of the select?
2303 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002304 if (match(FV, m_Zero()) &&
2305 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002306 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002307 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002308 if (match(TV, m_Zero()) &&
2309 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002310 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002311 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002312 }
2313 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002314
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002315 // Check for (add (sext x), y), see if we can merge this into an
2316 // integer add followed by a sext.
2317 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2318 // (add (sext x), cst) --> (sext (add x, cst'))
2319 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2320 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002321 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002322 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002323 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002324 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2325 // Insert the new, smaller add.
Chris Lattner74381062009-08-30 07:44:24 +00002326 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2327 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002328 return new SExtInst(NewAdd, I.getType());
2329 }
2330 }
2331
2332 // (add (sext x), (sext y)) --> (sext (add int x, y))
2333 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2334 // Only do this if x/y have the same type, if at last one of them has a
2335 // single use (so we don't increase the number of sexts), and if the
2336 // integer add will not overflow.
2337 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2338 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2339 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2340 RHSConv->getOperand(0))) {
2341 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002342 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2343 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002344 return new SExtInst(NewAdd, I.getType());
2345 }
2346 }
2347 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002348
2349 return Changed ? &I : 0;
2350}
2351
2352Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2353 bool Changed = SimplifyCommutative(I);
2354 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2355
2356 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2357 // X + 0 --> X
2358 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002359 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002360 (I.getType())->getValueAPF()))
2361 return ReplaceInstUsesWith(I, LHS);
2362 }
2363
2364 if (isa<PHINode>(LHS))
2365 if (Instruction *NV = FoldOpIntoPhi(I))
2366 return NV;
2367 }
2368
2369 // -A + B --> B - A
2370 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002371 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002372 return BinaryOperator::CreateFSub(RHS, LHSV);
2373
2374 // A + -B --> A - B
2375 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002376 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002377 return BinaryOperator::CreateFSub(LHS, V);
2378
2379 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2380 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2381 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2382 return ReplaceInstUsesWith(I, LHS);
2383
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002384 // Check for (add double (sitofp x), y), see if we can merge this into an
2385 // integer add followed by a promotion.
2386 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2387 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2388 // ... if the constant fits in the integer value. This is useful for things
2389 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2390 // requires a constant pool load, and generally allows the add to be better
2391 // instcombined.
2392 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2393 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002394 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002395 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002396 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002397 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2398 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002399 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2400 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002401 return new SIToFPInst(NewAdd, I.getType());
2402 }
2403 }
2404
2405 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2406 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2407 // Only do this if x/y have the same type, if at last one of them has a
2408 // single use (so we don't increase the number of int->fp conversions),
2409 // and if the integer add will not overflow.
2410 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2411 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2412 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2413 RHSConv->getOperand(0))) {
2414 // Insert the new integer add.
Chris Lattner74381062009-08-30 07:44:24 +00002415 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2416 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002417 return new SIToFPInst(NewAdd, I.getType());
2418 }
2419 }
2420 }
2421
Chris Lattner7e708292002-06-25 16:13:24 +00002422 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002423}
2424
Chris Lattner7e708292002-06-25 16:13:24 +00002425Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002427
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002428 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002429 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002430
Chris Lattner233f7dc2002-08-12 21:17:25 +00002431 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002432 if (Value *V = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002433 return BinaryOperator::CreateAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002434
Chris Lattnere87597f2004-10-16 18:11:37 +00002435 if (isa<UndefValue>(Op0))
2436 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2437 if (isa<UndefValue>(Op1))
2438 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2439
Chris Lattnerd65460f2003-11-05 01:06:05 +00002440 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2441 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002442 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002443 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002444
Chris Lattnerd65460f2003-11-05 01:06:05 +00002445 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002446 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002447 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002448 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002449
Chris Lattner76b7a062007-01-15 07:02:54 +00002450 // -(X >>u 31) -> (X >>s 31)
2451 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002452 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002453 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002454 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002455 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002456 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002457 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002458 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002459 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002460 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002461 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002462 }
2463 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002464 }
2465 else if (SI->getOpcode() == Instruction::AShr) {
2466 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2467 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002468 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002469 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002470 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002471 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002472 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002473 }
2474 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002475 }
2476 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002477 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002478
2479 // Try to fold constant sub into select arguments.
2480 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002481 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002482 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002483
2484 // C - zext(bool) -> bool ? C - 1 : C
2485 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002486 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002487 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002488 }
2489
Owen Anderson1d0be152009-08-13 21:58:54 +00002490 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002491 return BinaryOperator::CreateXor(Op0, Op1);
2492
Chris Lattner43d84d62005-04-07 16:15:25 +00002493 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002494 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002495 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002496 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002497 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002498 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002499 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002500 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002501 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2502 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2503 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002504 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002505 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002506 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002507 }
2508
Chris Lattnerfd059242003-10-15 16:48:29 +00002509 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002510 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2511 // is not used by anyone else...
2512 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002513 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002514 // Swap the two operands of the subexpr...
2515 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2516 Op1I->setOperand(0, IIOp1);
2517 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002518
Chris Lattnera2881962003-02-18 19:28:33 +00002519 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002520 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002521 }
2522
2523 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2524 //
2525 if (Op1I->getOpcode() == Instruction::And &&
2526 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2527 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2528
Chris Lattner74381062009-08-30 07:44:24 +00002529 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002530 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002531 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002532
Reid Spencerac5209e2006-10-16 23:08:08 +00002533 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002534 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002535 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002536 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002537 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002539 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002540
Chris Lattnerad3448c2003-02-18 19:57:07 +00002541 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002542 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002543 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002544 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002545 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002546 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002547 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002548 }
Chris Lattner40371712002-05-09 01:29:19 +00002549 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002550 }
Chris Lattnera2881962003-02-18 19:28:33 +00002551
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002552 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2553 if (Op0I->getOpcode() == Instruction::Add) {
2554 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2555 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2556 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2557 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2558 } else if (Op0I->getOpcode() == Instruction::Sub) {
2559 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002560 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002561 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002562 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002563 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002564
Chris Lattner50af16a2004-11-13 19:50:12 +00002565 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002566 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002567 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002568 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002569
Chris Lattner50af16a2004-11-13 19:50:12 +00002570 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002571 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002572 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002573 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002574 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002575}
2576
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002577Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2578 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2579
2580 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002581 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002582 return BinaryOperator::CreateFAdd(Op0, V);
2583
2584 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2585 if (Op1I->getOpcode() == Instruction::FAdd) {
2586 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002587 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002588 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002589 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002590 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002591 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002592 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002593 }
2594
2595 return 0;
2596}
2597
Chris Lattnera0141b92007-07-15 20:42:37 +00002598/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2599/// comparison only checks the sign bit. If it only checks the sign bit, set
2600/// TrueIfSigned if the result of the comparison is true when the input value is
2601/// signed.
2602static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2603 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002604 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002605 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2606 TrueIfSigned = true;
2607 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002608 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2609 TrueIfSigned = true;
2610 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002611 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2612 TrueIfSigned = false;
2613 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002614 case ICmpInst::ICMP_UGT:
2615 // True if LHS u> RHS and RHS == high-bit-mask - 1
2616 TrueIfSigned = true;
2617 return RHS->getValue() ==
2618 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2619 case ICmpInst::ICMP_UGE:
2620 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2621 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002622 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002623 default:
2624 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002625 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002626}
2627
Chris Lattner7e708292002-06-25 16:13:24 +00002628Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002629 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002630 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002631
Eli Friedman1694e092009-07-18 09:12:15 +00002632 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002633 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002634
Chris Lattner233f7dc2002-08-12 21:17:25 +00002635 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002636 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2637 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002638
2639 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002640 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002641 if (SI->getOpcode() == Instruction::Shl)
2642 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002643 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002644 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002645
Zhou Sheng843f07672007-04-19 05:39:12 +00002646 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002647 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2648 if (CI->equalsInt(1)) // X * 1 == X
2649 return ReplaceInstUsesWith(I, Op0);
2650 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002651 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002652
Zhou Sheng97b52c22007-03-29 01:57:21 +00002653 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002654 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002655 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00002656 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002657 }
Chris Lattnerb8cd4d32008-08-11 22:06:05 +00002658 } else if (isa<VectorType>(Op1->getType())) {
Eli Friedmanb4687092009-07-14 02:01:53 +00002659 if (Op1->isNullValue())
2660 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky895f0852008-11-27 20:21:08 +00002661
2662 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2663 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00002664 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00002665
2666 // As above, vector X*splat(1.0) -> X in all defined cases.
2667 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00002668 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2669 if (CI->equalsInt(1))
2670 return ReplaceInstUsesWith(I, Op0);
2671 }
2672 }
Chris Lattnera2881962003-02-18 19:28:33 +00002673 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002674
2675 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2676 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner47c99092008-05-18 04:11:26 +00002677 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002678 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattner74381062009-08-30 07:44:24 +00002679 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2680 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002681 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002682
2683 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002684
2685 // Try to fold constant mul into select arguments.
2686 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002687 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002688 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002689
2690 if (isa<PHINode>(Op0))
2691 if (Instruction *NV = FoldOpIntoPhi(I))
2692 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002693 }
2694
Dan Gohman186a6362009-08-12 16:04:34 +00002695 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2696 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002697 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002698
Nick Lewycky0c730792008-11-21 07:33:58 +00002699 // (X / Y) * Y = X - (X % Y)
2700 // (X / Y) * -Y = (X % Y) - X
2701 {
2702 Value *Op1 = I.getOperand(1);
2703 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2704 if (!BO ||
2705 (BO->getOpcode() != Instruction::UDiv &&
2706 BO->getOpcode() != Instruction::SDiv)) {
2707 Op1 = Op0;
2708 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2709 }
Dan Gohman186a6362009-08-12 16:04:34 +00002710 Value *Neg = dyn_castNegVal(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00002711 if (BO && BO->hasOneUse() &&
2712 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2713 (BO->getOpcode() == Instruction::UDiv ||
2714 BO->getOpcode() == Instruction::SDiv)) {
2715 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2716
Dan Gohmanfa94b942009-08-12 16:33:09 +00002717 // If the division is exact, X % Y is zero.
2718 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2719 if (SDiv->isExact()) {
2720 if (Op1BO == Op1)
2721 return ReplaceInstUsesWith(I, Op0BO);
2722 else
2723 return BinaryOperator::CreateNeg(Op0BO);
2724 }
2725
Chris Lattner74381062009-08-30 07:44:24 +00002726 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00002727 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00002728 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002729 else
Chris Lattner74381062009-08-30 07:44:24 +00002730 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002731 Rem->takeName(BO);
2732
2733 if (Op1BO == Op1)
2734 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00002735 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00002736 }
2737 }
2738
Owen Anderson1d0be152009-08-13 21:58:54 +00002739 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002740 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2741
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002742 // If one of the operands of the multiply is a cast from a boolean value, then
2743 // we know the bool is either zero or one, so this is a 'masking' multiply.
2744 // See if we can simplify things based on how the boolean was originally
2745 // formed.
2746 CastInst *BoolCast = 0;
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002747 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Owen Anderson1d0be152009-08-13 21:58:54 +00002748 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002749 BoolCast = CI;
2750 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002751 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00002752 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002753 BoolCast = CI;
2754 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002755 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002756 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2757 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002758 bool TIS = false;
2759
Reid Spencere4d87aa2006-12-23 06:05:41 +00002760 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002761 // multiply into a shift/and combination.
2762 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002763 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2764 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002765 // Shift the X value right to turn it into "all signbits".
Owen Andersoneed707b2009-07-24 23:12:02 +00002766 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002767 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner74381062009-08-30 07:44:24 +00002768 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2769 BoolCast->getOperand(0)->getName()+".mask");
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002770
2771 // If the multiply type is not the same as the source type, sign extend
2772 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002773 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002774 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2775 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002776 Instruction::CastOps opcode =
2777 (SrcBits == DstBits ? Instruction::BitCast :
2778 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2779 V = InsertCastBefore(opcode, V, I.getType(), I);
2780 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002781
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002782 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002783 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002784 }
2785 }
2786 }
2787
Chris Lattner7e708292002-06-25 16:13:24 +00002788 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002789}
2790
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002791Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2792 bool Changed = SimplifyCommutative(I);
2793 Value *Op0 = I.getOperand(0);
2794
2795 // Simplify mul instructions with a constant RHS...
2796 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2797 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2798 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2799 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2800 if (Op1F->isExactlyValue(1.0))
2801 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2802 } else if (isa<VectorType>(Op1->getType())) {
2803 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2804 // As above, vector X*splat(1.0) -> X in all defined cases.
2805 if (Constant *Splat = Op1V->getSplatValue()) {
2806 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2807 if (F->isExactlyValue(1.0))
2808 return ReplaceInstUsesWith(I, Op0);
2809 }
2810 }
2811 }
2812
2813 // Try to fold constant mul into select arguments.
2814 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2815 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2816 return R;
2817
2818 if (isa<PHINode>(Op0))
2819 if (Instruction *NV = FoldOpIntoPhi(I))
2820 return NV;
2821 }
2822
Dan Gohman186a6362009-08-12 16:04:34 +00002823 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2824 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002825 return BinaryOperator::CreateFMul(Op0v, Op1v);
2826
2827 return Changed ? &I : 0;
2828}
2829
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002830/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2831/// instruction.
2832bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2833 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2834
2835 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2836 int NonNullOperand = -1;
2837 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2838 if (ST->isNullValue())
2839 NonNullOperand = 2;
2840 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2841 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2842 if (ST->isNullValue())
2843 NonNullOperand = 1;
2844
2845 if (NonNullOperand == -1)
2846 return false;
2847
2848 Value *SelectCond = SI->getOperand(0);
2849
2850 // Change the div/rem to use 'Y' instead of the select.
2851 I.setOperand(1, SI->getOperand(NonNullOperand));
2852
2853 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2854 // problem. However, the select, or the condition of the select may have
2855 // multiple uses. Based on our knowledge that the operand must be non-zero,
2856 // propagate the known value for the select into other uses of it, and
2857 // propagate a known value of the condition into its other users.
2858
2859 // If the select and condition only have a single use, don't bother with this,
2860 // early exit.
2861 if (SI->use_empty() && SelectCond->hasOneUse())
2862 return true;
2863
2864 // Scan the current block backward, looking for other uses of SI.
2865 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2866
2867 while (BBI != BBFront) {
2868 --BBI;
2869 // If we found a call to a function, we can't assume it will return, so
2870 // information from below it cannot be propagated above it.
2871 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2872 break;
2873
2874 // Replace uses of the select or its condition with the known values.
2875 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2876 I != E; ++I) {
2877 if (*I == SI) {
2878 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002879 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002880 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00002881 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2882 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00002883 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002884 }
2885 }
2886
2887 // If we past the instruction, quit looking for it.
2888 if (&*BBI == SI)
2889 SI = 0;
2890 if (&*BBI == SelectCond)
2891 SelectCond = 0;
2892
2893 // If we ran out of things to eliminate, break out of the loop.
2894 if (SelectCond == 0 && SI == 0)
2895 break;
2896
2897 }
2898 return true;
2899}
2900
2901
Reid Spencer1628cec2006-10-26 06:15:43 +00002902/// This function implements the transforms on div instructions that work
2903/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2904/// used by the visitors to those instructions.
2905/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002906Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002907 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002908
Chris Lattner50b2ca42008-02-19 06:12:18 +00002909 // undef / X -> 0 for integer.
2910 // undef / X -> undef for FP (the undef could be a snan).
2911 if (isa<UndefValue>(Op0)) {
2912 if (Op0->getType()->isFPOrFPVector())
2913 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00002914 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002915 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002916
2917 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002918 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002919 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002920
Reid Spencer1628cec2006-10-26 06:15:43 +00002921 return 0;
2922}
Misha Brukmanfd939082005-04-21 23:48:37 +00002923
Reid Spencer1628cec2006-10-26 06:15:43 +00002924/// This function implements the transforms common to both integer division
2925/// instructions (udiv and sdiv). It is called by the visitors to those integer
2926/// division instructions.
2927/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002928Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002929 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2930
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002931 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002932 if (Op0 == Op1) {
2933 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00002934 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002935 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00002936 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002937 }
2938
Owen Andersoneed707b2009-07-24 23:12:02 +00002939 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00002940 return ReplaceInstUsesWith(I, CI);
2941 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00002942
Reid Spencer1628cec2006-10-26 06:15:43 +00002943 if (Instruction *Common = commonDivTransforms(I))
2944 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00002945
2946 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2947 // This does not apply for fdiv.
2948 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2949 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00002950
2951 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2952 // div X, 1 == X
2953 if (RHS->equalsInt(1))
2954 return ReplaceInstUsesWith(I, Op0);
2955
2956 // (X / C1) / C2 -> X / (C1*C2)
2957 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2958 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2959 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002960 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00002961 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00002962 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002963 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002964 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002965 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002966 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002967
Reid Spencerbca0e382007-03-23 20:05:17 +00002968 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2971 return R;
2972 if (isa<PHINode>(Op0))
2973 if (Instruction *NV = FoldOpIntoPhi(I))
2974 return NV;
2975 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002976 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002977
Chris Lattnera2881962003-02-18 19:28:33 +00002978 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002979 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002980 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00002981 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00002982
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002983 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00002984 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002985 return ReplaceInstUsesWith(I, Op0);
2986
Nick Lewycky895f0852008-11-27 20:21:08 +00002987 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2988 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2989 // div X, 1 == X
2990 if (X->isOne())
2991 return ReplaceInstUsesWith(I, Op0);
2992 }
2993
Reid Spencer1628cec2006-10-26 06:15:43 +00002994 return 0;
2995}
2996
2997Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2998 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2999
3000 // Handle the integer div common cases
3001 if (Instruction *Common = commonIDivTransforms(I))
3002 return Common;
3003
Reid Spencer1628cec2006-10-26 06:15:43 +00003004 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003005 // X udiv C^2 -> X >> C
3006 // Check to see if this is an unsigned division with an exact power of 2,
3007 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003008 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003009 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003010 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003011
3012 // X udiv C, where C >= signbit
3013 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003014 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003015 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003016 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003017 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003018 }
3019
3020 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003021 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003022 if (RHSI->getOpcode() == Instruction::Shl &&
3023 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003024 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003025 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003026 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003027 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003028 if (uint32_t C2 = C1.logBase2())
3029 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003031 }
3032 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003033 }
3034
Reid Spencer1628cec2006-10-26 06:15:43 +00003035 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3036 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003037 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003038 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003039 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003040 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003041 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003042 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003043 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003044 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003045 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003046 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003047
3048 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003049 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003050 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003051
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003052 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003053 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003054 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003055 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003056 return 0;
3057}
3058
Reid Spencer1628cec2006-10-26 06:15:43 +00003059Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3061
3062 // Handle the integer div common cases
3063 if (Instruction *Common = commonIDivTransforms(I))
3064 return Common;
3065
3066 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3067 // sdiv X, -1 == -X
3068 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003069 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003070
Dan Gohmanfa94b942009-08-12 16:33:09 +00003071 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003072 if (cast<SDivOperator>(&I)->isExact() &&
3073 RHS->getValue().isNonNegative() &&
3074 RHS->getValue().isPowerOf2()) {
3075 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3076 RHS->getValue().exactLogBase2());
3077 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3078 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003079
3080 // -X/C --> X/-C provided the negation doesn't overflow.
3081 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3082 if (isa<Constant>(Sub->getOperand(0)) &&
3083 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003084 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003085 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3086 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003087 }
3088
3089 // If the sign bits of both operands are zero (i.e. we can prove they are
3090 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003091 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003092 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003093 if (MaskedValueIsZero(Op0, Mask)) {
3094 if (MaskedValueIsZero(Op1, Mask)) {
3095 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3096 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3097 }
3098 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003099 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003100 ShiftedInt->getValue().isPowerOf2()) {
3101 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3102 // Safe because the only negative value (1 << Y) can take on is
3103 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3104 // the sign bit set.
3105 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3106 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003107 }
Eli Friedman8be17392009-07-18 09:53:21 +00003108 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003109
3110 return 0;
3111}
3112
3113Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3114 return commonDivTransforms(I);
3115}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003116
Reid Spencer0a783f72006-11-02 01:53:59 +00003117/// This function implements the transforms on rem instructions that work
3118/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3119/// is used by the visitors to those instructions.
3120/// @brief Transforms common to all three rem instructions
3121Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003122 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003123
Chris Lattner50b2ca42008-02-19 06:12:18 +00003124 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3125 if (I.getType()->isFPOrFPVector())
3126 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003127 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003128 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003129 if (isa<UndefValue>(Op1))
3130 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003131
3132 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003133 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3134 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003135
Reid Spencer0a783f72006-11-02 01:53:59 +00003136 return 0;
3137}
3138
3139/// This function implements the transforms common to both integer remainder
3140/// instructions (urem and srem). It is called by the visitors to those integer
3141/// remainder instructions.
3142/// @brief Common integer remainder transforms
3143Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3144 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3145
3146 if (Instruction *common = commonRemTransforms(I))
3147 return common;
3148
Dale Johannesened6af242009-01-21 00:35:19 +00003149 // 0 % X == 0 for integer, we don't need to preserve faults!
3150 if (Constant *LHS = dyn_cast<Constant>(Op0))
3151 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003152 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003153
Chris Lattner857e8cd2004-12-12 21:48:58 +00003154 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003155 // X % 0 == undef, we don't need to preserve faults!
3156 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003157 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003158
Chris Lattnera2881962003-02-18 19:28:33 +00003159 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003160 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003161
Chris Lattner97943922006-02-28 05:49:21 +00003162 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3163 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3164 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3165 return R;
3166 } else if (isa<PHINode>(Op0I)) {
3167 if (Instruction *NV = FoldOpIntoPhi(I))
3168 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003169 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003170
3171 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003172 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003173 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003174 }
Chris Lattnera2881962003-02-18 19:28:33 +00003175 }
3176
Reid Spencer0a783f72006-11-02 01:53:59 +00003177 return 0;
3178}
3179
3180Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3181 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3182
3183 if (Instruction *common = commonIRemTransforms(I))
3184 return common;
3185
3186 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3187 // X urem C^2 -> X and C
3188 // Check to see if this is an unsigned remainder with an exact power of 2,
3189 // if so, convert to a bitwise and.
3190 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003191 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003192 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003193 }
3194
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003195 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003196 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3197 if (RHSI->getOpcode() == Instruction::Shl &&
3198 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003199 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003200 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003201 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003202 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003203 }
3204 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003205 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003206
Reid Spencer0a783f72006-11-02 01:53:59 +00003207 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3208 // where C1&C2 are powers of two.
3209 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3210 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3211 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3212 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003213 if ((STO->getValue().isPowerOf2()) &&
3214 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003215 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3216 SI->getName()+".t");
3217 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3218 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003219 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003220 }
3221 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003222 }
3223
Chris Lattner3f5b8772002-05-06 16:14:14 +00003224 return 0;
3225}
3226
Reid Spencer0a783f72006-11-02 01:53:59 +00003227Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3229
Dan Gohmancff55092007-11-05 23:16:33 +00003230 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003231 if (Instruction *Common = commonIRemTransforms(I))
3232 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003233
Dan Gohman186a6362009-08-12 16:04:34 +00003234 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003235 if (!isa<Constant>(RHSNeg) ||
3236 (isa<ConstantInt>(RHSNeg) &&
3237 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003238 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003239 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003240 I.setOperand(1, RHSNeg);
3241 return &I;
3242 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003243
Dan Gohmancff55092007-11-05 23:16:33 +00003244 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003245 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003246 if (I.getType()->isInteger()) {
3247 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3248 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3249 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003250 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003251 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003252 }
3253
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003254 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003255 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3256 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003257
Nick Lewycky9dce8732008-12-20 16:48:00 +00003258 bool hasNegative = false;
3259 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3260 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3261 if (RHS->getValue().isNegative())
3262 hasNegative = true;
3263
3264 if (hasNegative) {
3265 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003266 for (unsigned i = 0; i != VWidth; ++i) {
3267 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3268 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003269 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003270 else
3271 Elts[i] = RHS;
3272 }
3273 }
3274
Owen Andersonaf7ec972009-07-28 21:19:26 +00003275 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003276 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003277 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003278 I.setOperand(1, NewRHSV);
3279 return &I;
3280 }
3281 }
3282 }
3283
Reid Spencer0a783f72006-11-02 01:53:59 +00003284 return 0;
3285}
3286
3287Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003288 return commonRemTransforms(I);
3289}
3290
Chris Lattner457dd822004-06-09 07:59:58 +00003291// isOneBitSet - Return true if there is exactly one bit set in the specified
3292// constant.
3293static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003294 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003295}
3296
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003297// isHighOnes - Return true if the constant is of the form 1+0+.
3298// This is the same as lowones(~X).
3299static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003300 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003301}
3302
Reid Spencere4d87aa2006-12-23 06:05:41 +00003303/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003304/// are carefully arranged to allow folding of expressions such as:
3305///
3306/// (A < B) | (A > B) --> (A != B)
3307///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003308/// Note that this is only valid if the first and second predicates have the
3309/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003310///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003311/// Three bits are used to represent the condition, as follows:
3312/// 0 A > B
3313/// 1 A == B
3314/// 2 A < B
3315///
3316/// <=> Value Definition
3317/// 000 0 Always false
3318/// 001 1 A > B
3319/// 010 2 A == B
3320/// 011 3 A >= B
3321/// 100 4 A < B
3322/// 101 5 A != B
3323/// 110 6 A <= B
3324/// 111 7 Always true
3325///
3326static unsigned getICmpCode(const ICmpInst *ICI) {
3327 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003328 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003329 case ICmpInst::ICMP_UGT: return 1; // 001
3330 case ICmpInst::ICMP_SGT: return 1; // 001
3331 case ICmpInst::ICMP_EQ: return 2; // 010
3332 case ICmpInst::ICMP_UGE: return 3; // 011
3333 case ICmpInst::ICMP_SGE: return 3; // 011
3334 case ICmpInst::ICMP_ULT: return 4; // 100
3335 case ICmpInst::ICMP_SLT: return 4; // 100
3336 case ICmpInst::ICMP_NE: return 5; // 101
3337 case ICmpInst::ICMP_ULE: return 6; // 110
3338 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003339 // True -> 7
3340 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003341 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003342 return 0;
3343 }
3344}
3345
Evan Cheng8db90722008-10-14 17:15:11 +00003346/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3347/// predicate into a three bit mask. It also returns whether it is an ordered
3348/// predicate by reference.
3349static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3350 isOrdered = false;
3351 switch (CC) {
3352 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3353 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003354 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3355 case FCmpInst::FCMP_UGT: return 1; // 001
3356 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3357 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003358 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3359 case FCmpInst::FCMP_UGE: return 3; // 011
3360 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3361 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003362 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3363 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003364 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3365 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003366 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003367 default:
3368 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003369 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003370 return 0;
3371 }
3372}
3373
Reid Spencere4d87aa2006-12-23 06:05:41 +00003374/// getICmpValue - This is the complement of getICmpCode, which turns an
3375/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003376/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003377/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003378static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003379 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003380 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003381 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003382 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003383 case 1:
3384 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003385 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003386 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003387 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3388 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003389 case 3:
3390 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003391 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003392 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003393 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003394 case 4:
3395 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003396 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003397 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003398 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3399 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003400 case 6:
3401 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003402 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003403 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003404 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003405 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003406 }
3407}
3408
Evan Cheng8db90722008-10-14 17:15:11 +00003409/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3410/// opcode and two operands into either a FCmp instruction. isordered is passed
3411/// in to determine which kind of predicate to use in the new fcmp instruction.
3412static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003413 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003414 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003415 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003416 case 0:
3417 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003418 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003419 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003420 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003421 case 1:
3422 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003423 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003424 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003425 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003426 case 2:
3427 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003428 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003429 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003430 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003431 case 3:
3432 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003433 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003434 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003435 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003436 case 4:
3437 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003438 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003439 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003440 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003441 case 5:
3442 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003443 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003444 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003445 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003446 case 6:
3447 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003448 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003449 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003450 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003451 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003452 }
3453}
3454
Chris Lattnerb9553d62008-11-16 04:55:20 +00003455/// PredicatesFoldable - Return true if both predicates match sign or if at
3456/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003457static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3458 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattnerb9553d62008-11-16 04:55:20 +00003459 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3460 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003461}
3462
3463namespace {
3464// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3465struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003466 InstCombiner &IC;
3467 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003468 ICmpInst::Predicate pred;
3469 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3470 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3471 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003472 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003473 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3474 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003475 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3476 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003477 return false;
3478 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003479 Instruction *apply(Instruction &Log) const {
3480 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3481 if (ICI->getOperand(0) != LHS) {
3482 assert(ICI->getOperand(1) == LHS);
3483 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003484 }
3485
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003486 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003487 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003488 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003489 unsigned Code;
3490 switch (Log.getOpcode()) {
3491 case Instruction::And: Code = LHSCode & RHSCode; break;
3492 case Instruction::Or: Code = LHSCode | RHSCode; break;
3493 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003494 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003495 }
3496
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003497 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3498 ICmpInst::isSignedPredicate(ICI->getPredicate());
3499
Owen Andersond672ecb2009-07-03 00:17:18 +00003500 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003501 if (Instruction *I = dyn_cast<Instruction>(RV))
3502 return I;
3503 // Otherwise, it's a constant boolean value...
3504 return IC.ReplaceInstUsesWith(Log, RV);
3505 }
3506};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003507} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003508
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003509// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3510// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003511// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003512Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003513 ConstantInt *OpRHS,
3514 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003515 BinaryOperator &TheAnd) {
3516 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003517 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003518 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003519 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003520
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003521 switch (Op->getOpcode()) {
3522 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003523 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003524 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003525 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003526 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003527 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003528 }
3529 break;
3530 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003531 if (Together == AndRHS) // (X | C) & C --> C
3532 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003533
Chris Lattner6e7ba452005-01-01 16:22:27 +00003534 if (Op->hasOneUse() && Together != OpRHS) {
3535 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003536 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003537 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003538 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003539 }
3540 break;
3541 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003542 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003543 // Adding a one to a single bit bit-field should be turned into an XOR
3544 // of the bit. First thing to check is to see if this AND is with a
3545 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003546 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003547
3548 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003549 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003550 // Ok, at this point, we know that we are masking the result of the
3551 // ADD down to exactly one bit. If the constant we are adding has
3552 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003553 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003554
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003555 // Check to see if any bits below the one bit set in AndRHSV are set.
3556 if ((AddRHS & (AndRHSV-1)) == 0) {
3557 // If not, the only thing that can effect the output of the AND is
3558 // the bit specified by AndRHSV. If that bit is set, the effect of
3559 // the XOR is to toggle the bit. If it is clear, then the ADD has
3560 // no effect.
3561 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3562 TheAnd.setOperand(0, X);
3563 return &TheAnd;
3564 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003565 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003566 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003567 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003568 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003569 }
3570 }
3571 }
3572 }
3573 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003574
3575 case Instruction::Shl: {
3576 // We know that the AND will not produce any of the bits shifted in, so if
3577 // the anded constant includes them, clear them now!
3578 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003579 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003580 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003581 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003582 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003583
Zhou Sheng290bec52007-03-29 08:15:12 +00003584 if (CI->getValue() == ShlMask) {
3585 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003586 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3587 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003588 TheAnd.setOperand(1, CI);
3589 return &TheAnd;
3590 }
3591 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003592 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003593 case Instruction::LShr:
3594 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003595 // We know that the AND will not produce any of the bits shifted in, so if
3596 // the anded constant includes them, clear them now! This only applies to
3597 // unsigned shifts, because a signed shr may bring in set bits!
3598 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003601 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003602 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003603
Zhou Sheng290bec52007-03-29 08:15:12 +00003604 if (CI->getValue() == ShrMask) {
3605 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003606 return ReplaceInstUsesWith(TheAnd, Op);
3607 } else if (CI != AndRHS) {
3608 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3609 return &TheAnd;
3610 }
3611 break;
3612 }
3613 case Instruction::AShr:
3614 // Signed shr.
3615 // See if this is shifting in some sign extension, then masking it out
3616 // with an and.
3617 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003618 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003619 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003620 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003621 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003622 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003623 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003624 // Make the argument unsigned.
3625 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003626 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003627 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003628 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003629 }
3630 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003631 }
3632 return 0;
3633}
3634
Chris Lattner8b170942002-08-09 23:47:40 +00003635
Chris Lattnera96879a2004-09-29 17:40:11 +00003636/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3637/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003638/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3639/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003640/// insert new instructions.
3641Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642 bool isSigned, bool Inside,
3643 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003644 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003645 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003646 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003647
Chris Lattnera96879a2004-09-29 17:40:11 +00003648 if (Inside) {
3649 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003650 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003651
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003653 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003654 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003655 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003656 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003657 }
3658
3659 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003660 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003661 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003662 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003663 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003664 }
3665
3666 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003667 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003668
Reid Spencere4e40032007-03-21 23:19:50 +00003669 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00003670 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003671 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003672 ICmpInst::Predicate pred = (isSigned ?
3673 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003674 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003675 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003676
Reid Spencere4e40032007-03-21 23:19:50 +00003677 // Emit V-Lo >u Hi-1-Lo
3678 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00003679 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00003680 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003681 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003682 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003683}
3684
Chris Lattner7203e152005-09-18 07:22:02 +00003685// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3686// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3687// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3688// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003689static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003690 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003691 uint32_t BitWidth = Val->getType()->getBitWidth();
3692 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003693
3694 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003695 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003696 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003697 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003698 return true;
3699}
3700
Chris Lattner7203e152005-09-18 07:22:02 +00003701/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3702/// where isSub determines whether the operator is a sub. If we can fold one of
3703/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003704///
3705/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3706/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3707/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3708///
3709/// return (A +/- B).
3710///
3711Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003712 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003713 Instruction &I) {
3714 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3715 if (!LHSI || LHSI->getNumOperands() != 2 ||
3716 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3717
3718 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3719
3720 switch (LHSI->getOpcode()) {
3721 default: return 0;
3722 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00003723 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003724 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003725 if ((Mask->getValue().countLeadingZeros() +
3726 Mask->getValue().countPopulation()) ==
3727 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003728 break;
3729
3730 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3731 // part, we don't need any explicit masks to take them out of A. If that
3732 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003733 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003734 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003735 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003736 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003737 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003738 break;
3739 }
3740 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003741 return 0;
3742 case Instruction::Or:
3743 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003744 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003745 if ((Mask->getValue().countLeadingZeros() +
3746 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00003747 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003748 break;
3749 return 0;
3750 }
3751
Chris Lattnerc8e77562005-09-18 04:24:45 +00003752 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00003753 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3754 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00003755}
3756
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003757/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3758Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3759 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00003760 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003761 ConstantInt *LHSCst, *RHSCst;
3762 ICmpInst::Predicate LHSCC, RHSCC;
3763
Chris Lattnerea065fb2008-11-16 05:10:52 +00003764 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003765 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00003766 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00003767 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00003768 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003769 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00003770
3771 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3772 // where C is a power of 2
3773 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3774 LHSCst->getValue().isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00003775 Value *NewOr = Builder->CreateOr(Val, Val2);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003776 return new ICmpInst(LHSCC, NewOr, LHSCst);
Chris Lattnerea065fb2008-11-16 05:10:52 +00003777 }
3778
3779 // From here on, we only handle:
3780 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3781 if (Val != Val2) return 0;
3782
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003783 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3784 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3785 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3786 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3787 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3788 return 0;
3789
3790 // We can't fold (ugt x, C) & (sgt x, C2).
3791 if (!PredicatesFoldable(LHSCC, RHSCC))
3792 return 0;
3793
3794 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00003795 bool ShouldSwap;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003796 if (ICmpInst::isSignedPredicate(LHSCC) ||
3797 (ICmpInst::isEquality(LHSCC) &&
3798 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00003799 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003800 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00003801 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3802
3803 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003804 std::swap(LHS, RHS);
3805 std::swap(LHSCst, RHSCst);
3806 std::swap(LHSCC, RHSCC);
3807 }
3808
3809 // At this point, we know we have have two icmp instructions
3810 // comparing a value against two constants and and'ing the result
3811 // together. Because of the above check, we know that we only have
3812 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3813 // (from the FoldICmpLogical check above), that the two constants
3814 // are not equal and that the larger constant is on the RHS
3815 assert(LHSCst != RHSCst && "Compares not folded above?");
3816
3817 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003818 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003819 case ICmpInst::ICMP_EQ:
3820 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003821 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003822 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3823 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3824 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003825 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003826 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3827 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3828 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3829 return ReplaceInstUsesWith(I, LHS);
3830 }
3831 case ICmpInst::ICMP_NE:
3832 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003833 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003834 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00003835 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003836 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003837 break; // (X != 13 & X u< 15) -> no change
3838 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00003839 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003840 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003841 break; // (X != 13 & X s< 15) -> no change
3842 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3843 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3844 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3845 return ReplaceInstUsesWith(I, RHS);
3846 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003847 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00003848 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00003849 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003850 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00003851 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003852 }
3853 break; // (X != 13 & X != 15) -> no change
3854 }
3855 break;
3856 case ICmpInst::ICMP_ULT:
3857 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003858 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003859 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3860 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003861 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003862 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3863 break;
3864 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3865 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3866 return ReplaceInstUsesWith(I, LHS);
3867 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3868 break;
3869 }
3870 break;
3871 case ICmpInst::ICMP_SLT:
3872 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003873 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003874 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3875 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00003876 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003877 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3878 break;
3879 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3880 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3881 return ReplaceInstUsesWith(I, LHS);
3882 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3883 break;
3884 }
3885 break;
3886 case ICmpInst::ICMP_UGT:
3887 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003888 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003889 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3890 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3891 return ReplaceInstUsesWith(I, RHS);
3892 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3893 break;
3894 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003895 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003896 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003897 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003898 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00003899 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003900 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003901 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3902 break;
3903 }
3904 break;
3905 case ICmpInst::ICMP_SGT:
3906 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003907 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003908 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3909 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3910 return ReplaceInstUsesWith(I, RHS);
3911 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3912 break;
3913 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00003914 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003915 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003916 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00003917 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00003918 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00003919 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003920 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3921 break;
3922 }
3923 break;
3924 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00003925
3926 return 0;
3927}
3928
Chris Lattner42d1be02009-07-23 05:14:02 +00003929Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3930 FCmpInst *RHS) {
3931
3932 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3933 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3934 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3935 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3936 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3937 // If either of the constants are nans, then the whole thing returns
3938 // false.
3939 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00003940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003941 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00003942 LHS->getOperand(0), RHS->getOperand(0));
3943 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00003944
3945 // Handle vector zeros. This occurs because the canonical form of
3946 // "fcmp ord x,x" is "fcmp ord x, 0".
3947 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3948 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003949 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00003950 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00003951 return 0;
3952 }
3953
3954 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3955 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3956 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3957
3958
3959 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3960 // Swap RHS operands to match LHS.
3961 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3962 std::swap(Op1LHS, Op1RHS);
3963 }
3964
3965 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3966 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3967 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003968 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00003969
3970 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00003971 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003972 if (Op0CC == FCmpInst::FCMP_TRUE)
3973 return ReplaceInstUsesWith(I, RHS);
3974 if (Op1CC == FCmpInst::FCMP_TRUE)
3975 return ReplaceInstUsesWith(I, LHS);
3976
3977 bool Op0Ordered;
3978 bool Op1Ordered;
3979 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3980 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3981 if (Op1Pred == 0) {
3982 std::swap(LHS, RHS);
3983 std::swap(Op0Pred, Op1Pred);
3984 std::swap(Op0Ordered, Op1Ordered);
3985 }
3986 if (Op0Pred == 0) {
3987 // uno && ueq -> uno && (uno || eq) -> ueq
3988 // ord && olt -> ord && (ord && lt) -> olt
3989 if (Op0Ordered == Op1Ordered)
3990 return ReplaceInstUsesWith(I, RHS);
3991
3992 // uno && oeq -> uno && (ord && eq) -> false
3993 // uno && ord -> false
3994 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00003995 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00003996 // ord && ueq -> ord && (uno || eq) -> oeq
3997 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3998 Op0LHS, Op0RHS, Context));
3999 }
4000 }
4001
4002 return 0;
4003}
4004
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004005
Chris Lattner7e708292002-06-25 16:13:24 +00004006Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004007 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004008 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004009
Chris Lattnere87597f2004-10-16 18:11:37 +00004010 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004011 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004012
Chris Lattner6e7ba452005-01-01 16:22:27 +00004013 // and X, X = X
4014 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004015 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004016
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004017 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004018 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004019 if (SimplifyDemandedInstructionBits(I))
4020 return &I;
4021 if (isa<VectorType>(I.getType())) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00004022 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00004023 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00004024 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00004025 } else if (isa<ConstantAggregateZero>(Op1)) {
4026 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00004027 }
4028 }
Dan Gohman6de29f82009-06-15 22:12:54 +00004029
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004030 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004031 const APInt& AndRHSMask = AndRHS->getValue();
4032 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004033
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004034 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00004035 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004036 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004037 Value *Op0LHS = Op0I->getOperand(0);
4038 Value *Op0RHS = Op0I->getOperand(1);
4039 switch (Op0I->getOpcode()) {
4040 case Instruction::Xor:
4041 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004042 // If the mask is only needed on one incoming arm, push it up.
4043 if (Op0I->hasOneUse()) {
4044 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4045 // Not masking anything out for the LHS, move to RHS.
Chris Lattner74381062009-08-30 07:44:24 +00004046 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4047 Op0RHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004048 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004049 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00004050 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00004051 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00004052 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4053 // Not masking anything out for the RHS, move to LHS.
Chris Lattner74381062009-08-30 07:44:24 +00004054 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4055 Op0LHS->getName()+".masked");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004056 return BinaryOperator::Create(
Chris Lattnerad1e3022005-01-23 20:26:55 +00004057 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4058 }
4059 }
4060
Chris Lattner6e7ba452005-01-01 16:22:27 +00004061 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004062 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004063 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4064 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4065 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4066 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004067 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004068 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004069 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004070 break;
4071
4072 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004073 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4074 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4075 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4076 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004077 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004078
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004079 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4080 // has 1's for all bits that the subtraction with A might affect.
4081 if (Op0I->hasOneUse()) {
4082 uint32_t BitWidth = AndRHSMask.getBitWidth();
4083 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4084 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4085
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004086 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004087 if (!(A && A->isZero()) && // avoid infinite recursion.
4088 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004089 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004090 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4091 }
4092 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004093 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004094
4095 case Instruction::Shl:
4096 case Instruction::LShr:
4097 // (1 << x) & 1 --> zext(x == 0)
4098 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004099 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004100 Value *NewICmp =
4101 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004102 return new ZExtInst(NewICmp, I.getType());
4103 }
4104 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004105 }
4106
Chris Lattner58403262003-07-23 19:25:52 +00004107 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004108 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004109 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004110 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004111 // If this is an integer truncation or change from signed-to-unsigned, and
4112 // if the source is an and/or with immediate, transform it. This
4113 // frequently occurs for bitfield accesses.
4114 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004115 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004116 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004117 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004118 if (CastOp->getOpcode() == Instruction::And) {
4119 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004120 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4121 // This will fold the two constants together, which may allow
4122 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004123 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004124 CastOp->getOperand(0), I.getType(),
4125 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004126 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004127 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004128 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004129 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004130 } else if (CastOp->getOpcode() == Instruction::Or) {
4131 // Change: and (cast (or X, C1) to T), C2
4132 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004133 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004134 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004135 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004136 return ReplaceInstUsesWith(I, AndRHS);
4137 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004138 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004139 }
Chris Lattner06782f82003-07-23 19:36:21 +00004140 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004141
4142 // Try to fold constant and into select arguments.
4143 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004144 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004145 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004146 if (isa<PHINode>(Op0))
4147 if (Instruction *NV = FoldOpIntoPhi(I))
4148 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004149 }
4150
Dan Gohman186a6362009-08-12 16:04:34 +00004151 Value *Op0NotVal = dyn_castNotVal(Op0);
4152 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00004153
Chris Lattner5b62aa72004-06-18 06:07:51 +00004154 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00004155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner5b62aa72004-06-18 06:07:51 +00004156
Misha Brukmancb6267b2004-07-30 12:50:08 +00004157 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00004158 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004159 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4160 I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004161 return BinaryOperator::CreateNot(Or);
Chris Lattnera2881962003-02-18 19:28:33 +00004162 }
Chris Lattner2082ad92006-02-13 23:07:23 +00004163
4164 {
Chris Lattner003b6202007-06-15 05:58:24 +00004165 Value *A = 0, *B = 0, *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004166 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004167 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4168 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00004169
4170 // (A|B) & ~(A&B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004171 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004172 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004173 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004174 }
4175 }
4176
Dan Gohman4ae51262009-08-12 16:23:25 +00004177 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00004178 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4179 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00004180
4181 // ~(A&B) & (A|B) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004182 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
Chris Lattner003b6202007-06-15 05:58:24 +00004183 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004184 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004185 }
4186 }
Chris Lattner64daab52006-04-01 08:03:55 +00004187
4188 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004189 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004190 if (A == Op1) { // (A^B)&A -> A&(A^B)
4191 I.swapOperands(); // Simplify below
4192 std::swap(Op0, Op1);
4193 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4194 cast<BinaryOperator>(Op0)->swapOperands();
4195 I.swapOperands(); // Simplify below
4196 std::swap(Op0, Op1);
4197 }
4198 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004199
Chris Lattner64daab52006-04-01 08:03:55 +00004200 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004201 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004202 if (B == Op0) { // B&(A^B) -> B&(B^A)
4203 cast<BinaryOperator>(Op1)->swapOperands();
4204 std::swap(A, B);
4205 }
Chris Lattner74381062009-08-30 07:44:24 +00004206 if (A == Op0) // A&(A^B) -> A & ~B
4207 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004208 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004209
4210 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004211 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4212 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004213 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004214 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4215 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004216 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004217 }
4218
Reid Spencere4d87aa2006-12-23 06:05:41 +00004219 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4220 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004221 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004222 return R;
4223
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004224 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4225 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4226 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004227 }
4228
Chris Lattner6fc205f2006-05-05 06:39:07 +00004229 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004230 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4231 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4232 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4233 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004234 if (SrcTy == Op1C->getOperand(0)->getType() &&
4235 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004236 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004237 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4238 I.getType(), TD) &&
4239 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4240 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004241 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4242 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004243 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004244 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004245 }
Chris Lattnere511b742006-11-14 07:46:50 +00004246
4247 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004248 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4249 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4250 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004251 SI0->getOperand(1) == SI1->getOperand(1) &&
4252 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004253 Value *NewOp =
4254 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4255 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004256 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004257 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004258 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004259 }
4260
Evan Cheng8db90722008-10-14 17:15:11 +00004261 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004262 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004263 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4264 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4265 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004266 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004267
Chris Lattner7e708292002-06-25 16:13:24 +00004268 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004269}
4270
Chris Lattner8c34cd22008-10-05 02:13:19 +00004271/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4272/// capable of providing pieces of a bswap. The subexpression provides pieces
4273/// of a bswap if it is proven that each of the non-zero bytes in the output of
4274/// the expression came from the corresponding "byte swapped" byte in some other
4275/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4276/// we know that the expression deposits the low byte of %X into the high byte
4277/// of the bswap result and that all other bytes are zero. This expression is
4278/// accepted, the high byte of ByteValues is set to X to indicate a correct
4279/// match.
4280///
4281/// This function returns true if the match was unsuccessful and false if so.
4282/// On entry to the function the "OverallLeftShift" is a signed integer value
4283/// indicating the number of bytes that the subexpression is later shifted. For
4284/// example, if the expression is later right shifted by 16 bits, the
4285/// OverallLeftShift value would be -2 on entry. This is used to specify which
4286/// byte of ByteValues is actually being set.
4287///
4288/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4289/// byte is masked to zero by a user. For example, in (X & 255), X will be
4290/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4291/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4292/// always in the local (OverallLeftShift) coordinate space.
4293///
4294static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4295 SmallVector<Value*, 8> &ByteValues) {
4296 if (Instruction *I = dyn_cast<Instruction>(V)) {
4297 // If this is an or instruction, it may be an inner node of the bswap.
4298 if (I->getOpcode() == Instruction::Or) {
4299 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4300 ByteValues) ||
4301 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4302 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004303 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004304
4305 // If this is a logical shift by a constant multiple of 8, recurse with
4306 // OverallLeftShift and ByteMask adjusted.
4307 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4308 unsigned ShAmt =
4309 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4310 // Ensure the shift amount is defined and of a byte value.
4311 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4312 return true;
4313
4314 unsigned ByteShift = ShAmt >> 3;
4315 if (I->getOpcode() == Instruction::Shl) {
4316 // X << 2 -> collect(X, +2)
4317 OverallLeftShift += ByteShift;
4318 ByteMask >>= ByteShift;
4319 } else {
4320 // X >>u 2 -> collect(X, -2)
4321 OverallLeftShift -= ByteShift;
4322 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004323 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004324 }
4325
4326 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4327 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4328
4329 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4330 ByteValues);
4331 }
4332
4333 // If this is a logical 'and' with a mask that clears bytes, clear the
4334 // corresponding bytes in ByteMask.
4335 if (I->getOpcode() == Instruction::And &&
4336 isa<ConstantInt>(I->getOperand(1))) {
4337 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4338 unsigned NumBytes = ByteValues.size();
4339 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4340 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4341
4342 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4343 // If this byte is masked out by a later operation, we don't care what
4344 // the and mask is.
4345 if ((ByteMask & (1 << i)) == 0)
4346 continue;
4347
4348 // If the AndMask is all zeros for this byte, clear the bit.
4349 APInt MaskB = AndMask & Byte;
4350 if (MaskB == 0) {
4351 ByteMask &= ~(1U << i);
4352 continue;
4353 }
4354
4355 // If the AndMask is not all ones for this byte, it's not a bytezap.
4356 if (MaskB != Byte)
4357 return true;
4358
4359 // Otherwise, this byte is kept.
4360 }
4361
4362 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4363 ByteValues);
4364 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004365 }
4366
Chris Lattner8c34cd22008-10-05 02:13:19 +00004367 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4368 // the input value to the bswap. Some observations: 1) if more than one byte
4369 // is demanded from this input, then it could not be successfully assembled
4370 // into a byteswap. At least one of the two bytes would not be aligned with
4371 // their ultimate destination.
4372 if (!isPowerOf2_32(ByteMask)) return true;
4373 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004374
Chris Lattner8c34cd22008-10-05 02:13:19 +00004375 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4376 // is demanded, it needs to go into byte 0 of the result. This means that the
4377 // byte needs to be shifted until it lands in the right byte bucket. The
4378 // shift amount depends on the position: if the byte is coming from the high
4379 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4380 // low part, it must be shifted left.
4381 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4382 if (InputByteNo < ByteValues.size()/2) {
4383 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4384 return true;
4385 } else {
4386 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4387 return true;
4388 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004389
4390 // If the destination byte value is already defined, the values are or'd
4391 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004392 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004393 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004394 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004395 return false;
4396}
4397
4398/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4399/// If so, insert the new bswap intrinsic and return it.
4400Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004401 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004402 if (!ITy || ITy->getBitWidth() % 16 ||
4403 // ByteMask only allows up to 32-byte values.
4404 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004405 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004406
4407 /// ByteValues - For each byte of the result, we keep track of which value
4408 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004409 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004410 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004411
4412 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004413 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4414 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004415 return 0;
4416
4417 // Check to see if all of the bytes come from the same value.
4418 Value *V = ByteValues[0];
4419 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4420
4421 // Check to make sure that all of the bytes come from the same value.
4422 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4423 if (ByteValues[i] != V)
4424 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004425 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004426 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004427 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004428 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004429}
4430
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004431/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4432/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4433/// we can simplify this expression to "cond ? C : D or B".
4434static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004435 Value *C, Value *D,
4436 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004437 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004438 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004439 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004440 return 0;
4441
Chris Lattnera6a474d2008-11-16 04:26:55 +00004442 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004443 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004444 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004445 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004446 return SelectInst::Create(Cond, C, B);
4447 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004448 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004449 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004450 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004451 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004452 return 0;
4453}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004454
Chris Lattner69d4ced2008-11-16 05:20:07 +00004455/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4456Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4457 ICmpInst *LHS, ICmpInst *RHS) {
4458 Value *Val, *Val2;
4459 ConstantInt *LHSCst, *RHSCst;
4460 ICmpInst::Predicate LHSCC, RHSCC;
4461
4462 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004463 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004464 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004465 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004466 m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004467 return 0;
4468
4469 // From here on, we only handle:
4470 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4471 if (Val != Val2) return 0;
4472
4473 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4474 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4475 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4476 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4477 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4478 return 0;
4479
4480 // We can't fold (ugt x, C) | (sgt x, C2).
4481 if (!PredicatesFoldable(LHSCC, RHSCC))
4482 return 0;
4483
4484 // Ensure that the larger constant is on the RHS.
4485 bool ShouldSwap;
4486 if (ICmpInst::isSignedPredicate(LHSCC) ||
4487 (ICmpInst::isEquality(LHSCC) &&
4488 ICmpInst::isSignedPredicate(RHSCC)))
4489 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4490 else
4491 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4492
4493 if (ShouldSwap) {
4494 std::swap(LHS, RHS);
4495 std::swap(LHSCst, RHSCst);
4496 std::swap(LHSCC, RHSCC);
4497 }
4498
4499 // At this point, we know we have have two icmp instructions
4500 // comparing a value against two constants and or'ing the result
4501 // together. Because of the above check, we know that we only have
4502 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4503 // FoldICmpLogical check above), that the two constants are not
4504 // equal.
4505 assert(LHSCst != RHSCst && "Compares not folded above?");
4506
4507 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004508 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004509 case ICmpInst::ICMP_EQ:
4510 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004511 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004512 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004513 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004514 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004515 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004516 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004517 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004518 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004519 }
4520 break; // (X == 13 | X == 15) -> no change
4521 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4522 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4523 break;
4524 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4525 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4526 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4527 return ReplaceInstUsesWith(I, RHS);
4528 }
4529 break;
4530 case ICmpInst::ICMP_NE:
4531 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004532 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004533 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4534 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4535 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4536 return ReplaceInstUsesWith(I, LHS);
4537 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4538 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4539 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004540 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004541 }
4542 break;
4543 case ICmpInst::ICMP_ULT:
4544 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004545 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004546 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4547 break;
4548 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4549 // If RHSCst is [us]MAXINT, it is always false. Not handling
4550 // this can cause overflow.
4551 if (RHSCst->isMaxValue(false))
4552 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004553 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004554 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004555 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4556 break;
4557 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4558 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4559 return ReplaceInstUsesWith(I, RHS);
4560 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4561 break;
4562 }
4563 break;
4564 case ICmpInst::ICMP_SLT:
4565 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004566 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004567 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4568 break;
4569 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4570 // If RHSCst is [us]MAXINT, it is always false. Not handling
4571 // this can cause overflow.
4572 if (RHSCst->isMaxValue(true))
4573 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004574 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004575 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004576 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4577 break;
4578 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4579 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4580 return ReplaceInstUsesWith(I, RHS);
4581 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4582 break;
4583 }
4584 break;
4585 case ICmpInst::ICMP_UGT:
4586 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004587 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004588 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4589 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4590 return ReplaceInstUsesWith(I, LHS);
4591 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4592 break;
4593 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4594 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004595 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004596 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4597 break;
4598 }
4599 break;
4600 case ICmpInst::ICMP_SGT:
4601 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004602 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004603 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4604 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4605 return ReplaceInstUsesWith(I, LHS);
4606 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4607 break;
4608 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4609 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004610 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004611 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4612 break;
4613 }
4614 break;
4615 }
4616 return 0;
4617}
4618
Chris Lattner5414cc52009-07-23 05:46:22 +00004619Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4620 FCmpInst *RHS) {
4621 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4622 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4623 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4624 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4625 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4626 // If either of the constants are nans, then the whole thing returns
4627 // true.
4628 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004629 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004630
4631 // Otherwise, no need to compare the two constants, compare the
4632 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004633 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004634 LHS->getOperand(0), RHS->getOperand(0));
4635 }
4636
4637 // Handle vector zeros. This occurs because the canonical form of
4638 // "fcmp uno x,x" is "fcmp uno x, 0".
4639 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4640 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004641 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004642 LHS->getOperand(0), RHS->getOperand(0));
4643
4644 return 0;
4645 }
4646
4647 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4648 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4649 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4650
4651 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4652 // Swap RHS operands to match LHS.
4653 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4654 std::swap(Op1LHS, Op1RHS);
4655 }
4656 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4657 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4658 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004659 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004660 Op0LHS, Op0RHS);
4661 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004663 if (Op0CC == FCmpInst::FCMP_FALSE)
4664 return ReplaceInstUsesWith(I, RHS);
4665 if (Op1CC == FCmpInst::FCMP_FALSE)
4666 return ReplaceInstUsesWith(I, LHS);
4667 bool Op0Ordered;
4668 bool Op1Ordered;
4669 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4670 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4671 if (Op0Ordered == Op1Ordered) {
4672 // If both are ordered or unordered, return a new fcmp with
4673 // or'ed predicates.
4674 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4675 Op0LHS, Op0RHS, Context);
4676 if (Instruction *I = dyn_cast<Instruction>(RV))
4677 return I;
4678 // Otherwise, it's a constant boolean value...
4679 return ReplaceInstUsesWith(I, RV);
4680 }
4681 }
4682 return 0;
4683}
4684
Bill Wendlinga698a472008-12-01 08:23:25 +00004685/// FoldOrWithConstants - This helper function folds:
4686///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004687/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00004688///
4689/// into:
4690///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004691/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00004692///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00004693/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00004694Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00004695 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00004696 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4697 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004698
Bill Wendling286a0542008-12-02 06:24:20 +00004699 Value *V1 = 0;
4700 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004701 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00004702
Bill Wendling29976b92008-12-02 06:18:11 +00004703 APInt Xor = CI1->getValue() ^ CI2->getValue();
4704 if (!Xor.isAllOnesValue()) return 0;
4705
Bill Wendling286a0542008-12-02 06:24:20 +00004706 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00004707 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00004708 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00004709 }
4710
4711 return 0;
4712}
4713
Chris Lattner7e708292002-06-25 16:13:24 +00004714Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004715 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004716 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004717
Chris Lattner42593e62007-03-24 23:56:43 +00004718 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004719 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004720
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004721 // or X, X = X
4722 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00004723 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004724
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004725 // See if we can simplify any instructions used by the instruction whose sole
4726 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004727 if (SimplifyDemandedInstructionBits(I))
4728 return &I;
4729 if (isa<VectorType>(I.getType())) {
4730 if (isa<ConstantAggregateZero>(Op1)) {
4731 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4732 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4733 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4734 return ReplaceInstUsesWith(I, I.getOperand(1));
4735 }
Chris Lattner42593e62007-03-24 23:56:43 +00004736 }
Chris Lattner041a6c92007-06-15 05:26:55 +00004737
Chris Lattner3f5b8772002-05-06 16:14:14 +00004738 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004739 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00004740 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004741 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004742 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004743 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004744 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004745 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004746 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004747 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004748 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004749
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004750 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00004751 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004752 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00004753 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00004754 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004755 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00004756 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004757 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004758
4759 // Try to fold constant and into select arguments.
4760 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004761 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004762 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004763 if (isa<PHINode>(Op0))
4764 if (Instruction *NV = FoldOpIntoPhi(I))
4765 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00004766 }
4767
Chris Lattner4f637d42006-01-06 17:59:59 +00004768 Value *A = 0, *B = 0;
4769 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004770
Dan Gohman4ae51262009-08-12 16:23:25 +00004771 if (match(Op0, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004772 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4773 return ReplaceInstUsesWith(I, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004774 if (match(Op1, m_And(m_Value(A), m_Value(B))))
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004775 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4776 return ReplaceInstUsesWith(I, Op0);
4777
Chris Lattner6423d4c2006-07-10 20:25:24 +00004778 // (A | B) | C and A | (B | C) -> bswap if possible.
4779 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00004780 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4781 match(Op1, m_Or(m_Value(), m_Value())) ||
4782 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4783 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004784 if (Instruction *BSwap = MatchBSwap(I))
4785 return BSwap;
4786 }
4787
Chris Lattner6e4c6492005-05-09 04:58:36 +00004788 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004789 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004790 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004791 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004792 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00004793 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004794 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004795 }
4796
4797 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004798 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004799 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004800 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00004801 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00004802 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004803 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004804 }
4805
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004806 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004807 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004808 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4809 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004810 Value *V1 = 0, *V2 = 0, *V3 = 0;
4811 C1 = dyn_cast<ConstantInt>(C);
4812 C2 = dyn_cast<ConstantInt>(D);
4813 if (C1 && C2) { // (A & C1)|(B & C2)
4814 // If we have: ((V + N) & C1) | (V & C2)
4815 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4816 // replace with V+N.
4817 if (C1->getValue() == ~C2->getValue()) {
4818 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00004819 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004820 // Add commutes, try both ways.
4821 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4822 return ReplaceInstUsesWith(I, A);
4823 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4824 return ReplaceInstUsesWith(I, A);
4825 }
4826 // Or commutes, try both ways.
4827 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004828 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004829 // Add commutes, try both ways.
4830 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4831 return ReplaceInstUsesWith(I, B);
4832 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4833 return ReplaceInstUsesWith(I, B);
4834 }
4835 }
Chris Lattner044e5332007-04-08 08:01:49 +00004836 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004837 }
4838
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004839 // Check to see if we have any common things being and'ed. If so, find the
4840 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004841 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4842 if (A == B) // (A & C)|(A & D) == A & (C|D)
4843 V1 = A, V2 = C, V3 = D;
4844 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4845 V1 = A, V2 = B, V3 = C;
4846 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4847 V1 = C, V2 = A, V3 = D;
4848 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4849 V1 = C, V2 = A, V3 = B;
4850
4851 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00004852 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004853 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004854 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004855 }
Dan Gohmanb493b272008-10-28 22:38:57 +00004856
Dan Gohman1975d032008-10-30 20:40:10 +00004857 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004858 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004859 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004860 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004861 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004862 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004863 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004864 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004865 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00004866
Bill Wendlingb01865c2008-11-30 13:52:49 +00004867 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004868 if ((match(C, m_Not(m_Specific(D))) &&
4869 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004870 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004871 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004872 if ((match(A, m_Not(m_Specific(D))) &&
4873 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004874 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004875 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004876 if ((match(C, m_Not(m_Specific(B))) &&
4877 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004878 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00004879 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00004880 if ((match(A, m_Not(m_Specific(B))) &&
4881 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00004882 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004883 }
Chris Lattnere511b742006-11-14 07:46:50 +00004884
4885 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004886 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4887 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4888 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004889 SI0->getOperand(1) == SI1->getOperand(1) &&
4890 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004891 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4892 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004893 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004894 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004895 }
4896 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004897
Bill Wendlingb3833d12008-12-01 01:07:11 +00004898 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004899 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4900 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004901 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004902 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004903 }
4904 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00004905 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4906 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00004907 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00004908 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00004909 }
4910
Dan Gohman4ae51262009-08-12 16:23:25 +00004911 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004912 if (A == Op1) // ~A | A == -1
Owen Andersona7235ea2009-07-31 20:28:14 +00004913 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004914 } else {
4915 A = 0;
4916 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004917 // Note, A is still live here!
Dan Gohman4ae51262009-08-12 16:23:25 +00004918 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004919 if (Op0 == B)
Owen Andersona7235ea2009-07-31 20:28:14 +00004920 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004921
Misha Brukmancb6267b2004-07-30 12:50:08 +00004922 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004923 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner74381062009-08-30 07:44:24 +00004924 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
Dan Gohman4ae51262009-08-12 16:23:25 +00004925 return BinaryOperator::CreateNot(And);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004926 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004927 }
Chris Lattnera2881962003-02-18 19:28:33 +00004928
Reid Spencere4d87aa2006-12-23 06:05:41 +00004929 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4930 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00004931 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004932 return R;
4933
Chris Lattner69d4ced2008-11-16 05:20:07 +00004934 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4935 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4936 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004937 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004938
4939 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004940 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004941 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004942 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00004943 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4944 !isa<ICmpInst>(Op1C->getOperand(0))) {
4945 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004946 if (SrcTy == Op1C->getOperand(0)->getType() &&
4947 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00004948 // Only do this if the casts both really cause code to be
4949 // generated.
4950 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4951 I.getType(), TD) &&
4952 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4953 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004954 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4955 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004956 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00004957 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004958 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004959 }
Chris Lattner99c65742007-10-24 05:38:08 +00004960 }
4961
4962
4963 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4964 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00004965 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4966 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4967 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004968 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004969
Chris Lattner7e708292002-06-25 16:13:24 +00004970 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004971}
4972
Dan Gohman844731a2008-05-13 00:00:25 +00004973namespace {
4974
Chris Lattnerc317d392004-02-16 01:20:27 +00004975// XorSelf - Implements: X ^ X --> 0
4976struct XorSelf {
4977 Value *RHS;
4978 XorSelf(Value *rhs) : RHS(rhs) {}
4979 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4980 Instruction *apply(BinaryOperator &Xor) const {
4981 return &Xor;
4982 }
4983};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004984
Dan Gohman844731a2008-05-13 00:00:25 +00004985}
Chris Lattner3f5b8772002-05-06 16:14:14 +00004986
Chris Lattner7e708292002-06-25 16:13:24 +00004987Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004988 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004989 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004990
Evan Chengd34af782008-03-25 20:07:13 +00004991 if (isa<UndefValue>(Op1)) {
4992 if (isa<UndefValue>(Op0))
4993 // Handle undef ^ undef -> 0 special case. This is a common
4994 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00004995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00004996 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00004997 }
Chris Lattnere87597f2004-10-16 18:11:37 +00004998
Chris Lattnerc317d392004-02-16 01:20:27 +00004999 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005000 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005001 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005002 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005003 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005004
5005 // See if we can simplify any instructions used by the instruction whose sole
5006 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005007 if (SimplifyDemandedInstructionBits(I))
5008 return &I;
5009 if (isa<VectorType>(I.getType()))
5010 if (isa<ConstantAggregateZero>(Op1))
5011 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005012
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005013 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005014 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005015 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5016 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5017 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5018 if (Op0I->getOpcode() == Instruction::And ||
5019 Op0I->getOpcode() == Instruction::Or) {
Dan Gohman186a6362009-08-12 16:04:34 +00005020 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5021 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005022 Value *NotY =
5023 Builder->CreateNot(Op0I->getOperand(1),
5024 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005025 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005026 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005027 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005028 }
5029 }
5030 }
5031 }
5032
5033
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005034 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson5defacc2009-07-31 17:39:07 +00005035 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005036 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005037 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005038 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005039 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005040
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005041 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005042 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005043 FCI->getOperand(0), FCI->getOperand(1));
5044 }
5045
Nick Lewycky517e1f52008-05-31 19:01:33 +00005046 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5047 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5048 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5049 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5050 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005051 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5052 (RHS == ConstantExpr::getCast(Opcode,
5053 ConstantInt::getTrue(*Context),
5054 Op0C->getDestTy()))) {
5055 CI->setPredicate(CI->getInversePredicate());
5056 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005057 }
5058 }
5059 }
5060 }
5061
Reid Spencere4d87aa2006-12-23 06:05:41 +00005062 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005063 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005064 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5065 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005066 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5067 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005068 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005069 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005070 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005071
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005072 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005073 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005074 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005075 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005076 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005077 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005078 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005079 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005080 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005081 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005082 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005083 Constant *C = ConstantInt::get(*Context,
5084 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005085 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005086
Chris Lattner7c4049c2004-01-12 19:35:11 +00005087 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005088 } else if (Op0I->getOpcode() == Instruction::Or) {
5089 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005090 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005091 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005092 // Anything in both C1 and C2 is known to be zero, remove it from
5093 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005094 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5095 NewRHS = ConstantExpr::getAnd(NewRHS,
5096 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005097 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005098 I.setOperand(0, Op0I->getOperand(0));
5099 I.setOperand(1, NewRHS);
5100 return &I;
5101 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005102 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005103 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005104 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005105
5106 // Try to fold constant and into select arguments.
5107 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005108 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005109 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005110 if (isa<PHINode>(Op0))
5111 if (Instruction *NV = FoldOpIntoPhi(I))
5112 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005113 }
5114
Dan Gohman186a6362009-08-12 16:04:34 +00005115 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005116 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005117 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005118
Dan Gohman186a6362009-08-12 16:04:34 +00005119 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005120 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005121 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005122
Chris Lattner318bf792007-03-18 22:51:34 +00005123
5124 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5125 if (Op1I) {
5126 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005127 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005128 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005129 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005130 I.swapOperands();
5131 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005132 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005133 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005134 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005135 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005136 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005137 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005138 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005139 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005140 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005141 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005142 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005143 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005144 std::swap(A, B);
5145 }
Chris Lattner318bf792007-03-18 22:51:34 +00005146 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005147 I.swapOperands(); // Simplified below.
5148 std::swap(Op0, Op1);
5149 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005150 }
Chris Lattner318bf792007-03-18 22:51:34 +00005151 }
5152
5153 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5154 if (Op0I) {
5155 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005156 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005157 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005158 if (A == Op1) // (B|A)^B == (A|B)^B
5159 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005160 if (B == Op1) // (A|B)^B == A & ~B
5161 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005162 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005163 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005164 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005165 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005166 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005167 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005168 if (A == Op1) // (A&B)^A -> (B&A)^A
5169 std::swap(A, B);
5170 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005171 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005172 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005173 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005174 }
Chris Lattner318bf792007-03-18 22:51:34 +00005175 }
5176
5177 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5178 if (Op0I && Op1I && Op0I->isShift() &&
5179 Op0I->getOpcode() == Op1I->getOpcode() &&
5180 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5181 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005182 Value *NewOp =
5183 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5184 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005185 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005186 Op1I->getOperand(1));
5187 }
5188
5189 if (Op0I && Op1I) {
5190 Value *A, *B, *C, *D;
5191 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005192 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5193 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005194 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005195 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005196 }
5197 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005198 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5199 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005200 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005201 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005202 }
5203
5204 // (A & B)^(C & D)
5205 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005206 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5207 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005208 // (X & Y)^(X & Y) -> (Y^Z) & X
5209 Value *X = 0, *Y = 0, *Z = 0;
5210 if (A == C)
5211 X = A, Y = B, Z = D;
5212 else if (A == D)
5213 X = A, Y = B, Z = C;
5214 else if (B == C)
5215 X = B, Y = A, Z = D;
5216 else if (B == D)
5217 X = B, Y = A, Z = C;
5218
5219 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005220 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005221 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005222 }
5223 }
5224 }
5225
Reid Spencere4d87aa2006-12-23 06:05:41 +00005226 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5227 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005228 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005229 return R;
5230
Chris Lattner6fc205f2006-05-05 06:39:07 +00005231 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005232 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005233 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005234 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5235 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005236 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005237 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005238 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5239 I.getType(), TD) &&
5240 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5241 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005242 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5243 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005244 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005245 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005246 }
Chris Lattner99c65742007-10-24 05:38:08 +00005247 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005248
Chris Lattner7e708292002-06-25 16:13:24 +00005249 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005250}
5251
Owen Andersond672ecb2009-07-03 00:17:18 +00005252static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005253 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005254 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005255}
Chris Lattnera96879a2004-09-29 17:40:11 +00005256
Dan Gohman6de29f82009-06-15 22:12:54 +00005257static bool HasAddOverflow(ConstantInt *Result,
5258 ConstantInt *In1, ConstantInt *In2,
5259 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005260 if (IsSigned)
5261 if (In2->getValue().isNegative())
5262 return Result->getValue().sgt(In1->getValue());
5263 else
5264 return Result->getValue().slt(In1->getValue());
5265 else
5266 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005267}
5268
Dan Gohman6de29f82009-06-15 22:12:54 +00005269/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005270/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005271static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005272 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005273 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005274 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005275
Dan Gohman6de29f82009-06-15 22:12:54 +00005276 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5277 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005278 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005279 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5280 ExtractElement(In1, Idx, Context),
5281 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005282 IsSigned))
5283 return true;
5284 }
5285 return false;
5286 }
5287
5288 return HasAddOverflow(cast<ConstantInt>(Result),
5289 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5290 IsSigned);
5291}
5292
5293static bool HasSubOverflow(ConstantInt *Result,
5294 ConstantInt *In1, ConstantInt *In2,
5295 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005296 if (IsSigned)
5297 if (In2->getValue().isNegative())
5298 return Result->getValue().slt(In1->getValue());
5299 else
5300 return Result->getValue().sgt(In1->getValue());
5301 else
5302 return Result->getValue().ugt(In1->getValue());
5303}
5304
Dan Gohman6de29f82009-06-15 22:12:54 +00005305/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5306/// overflowed for this type.
5307static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005308 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005309 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005310 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005311
5312 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5313 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005314 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005315 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5316 ExtractElement(In1, Idx, Context),
5317 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005318 IsSigned))
5319 return true;
5320 }
5321 return false;
5322 }
5323
5324 return HasSubOverflow(cast<ConstantInt>(Result),
5325 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5326 IsSigned);
5327}
5328
Chris Lattner574da9b2005-01-13 20:14:25 +00005329/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5330/// code necessary to compute the offset from the base pointer (without adding
5331/// in the base pointer). Return the result as a signed integer of intptr size.
5332static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005333 TargetData &TD = *IC.getTargetData();
Chris Lattner574da9b2005-01-13 20:14:25 +00005334 gep_type_iterator GTI = gep_type_begin(GEP);
Owen Anderson1d0be152009-08-13 21:58:54 +00005335 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
Owen Andersona7235ea2009-07-31 20:28:14 +00005336 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00005337
5338 // Build a mask for high order bits.
Chris Lattner10c0d912008-04-22 02:53:33 +00005339 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chris Lattnere62f0212007-04-28 04:52:43 +00005340 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00005341
Gabor Greif177dd3f2008-06-12 21:37:33 +00005342 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5343 ++i, ++GTI) {
5344 Value *Op = *i;
Duncan Sands777d2302009-05-09 07:06:46 +00005345 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00005346 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5347 if (OpC->isZero()) continue;
5348
5349 // Handle a struct index, which adds its field offset to the pointer.
5350 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5351 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5352
Chris Lattner74381062009-08-30 07:44:24 +00005353 Result = IC.Builder->CreateAdd(Result,
5354 ConstantInt::get(IntPtrTy, Size),
5355 GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005356 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00005357 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005358
Owen Andersoneed707b2009-07-24 23:12:02 +00005359 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Owen Andersond672ecb2009-07-03 00:17:18 +00005360 Constant *OC =
Owen Andersonbaf3c402009-07-29 18:55:55 +00005361 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5362 Scale = ConstantExpr::getMul(OC, Scale);
Chris Lattner74381062009-08-30 07:44:24 +00005363 // Emit an add instruction.
5364 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
Chris Lattnere62f0212007-04-28 04:52:43 +00005365 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00005366 }
Chris Lattnere62f0212007-04-28 04:52:43 +00005367 // Convert to correct type.
Chris Lattner74381062009-08-30 07:44:24 +00005368 if (Op->getType() != IntPtrTy)
5369 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
Chris Lattnere62f0212007-04-28 04:52:43 +00005370 if (Size != 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00005371 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
Chris Lattner74381062009-08-30 07:44:24 +00005372 // We'll let instcombine(mul) convert this to a shl if possible.
5373 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
Chris Lattnere62f0212007-04-28 04:52:43 +00005374 }
5375
5376 // Emit an add instruction.
Chris Lattner74381062009-08-30 07:44:24 +00005377 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
Chris Lattner574da9b2005-01-13 20:14:25 +00005378 }
5379 return Result;
5380}
5381
Chris Lattner10c0d912008-04-22 02:53:33 +00005382
Dan Gohman8f080f02009-07-17 22:16:21 +00005383/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5384/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5385/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5386/// be complex, and scales are involved. The above expression would also be
5387/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5388/// This later form is less amenable to optimization though, and we are allowed
5389/// to generate the first by knowing that pointer arithmetic doesn't overflow.
Chris Lattner10c0d912008-04-22 02:53:33 +00005390///
5391/// If we can't emit an optimized form for this expression, this returns null.
5392///
5393static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5394 InstCombiner &IC) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005395 TargetData &TD = *IC.getTargetData();
Chris Lattner10c0d912008-04-22 02:53:33 +00005396 gep_type_iterator GTI = gep_type_begin(GEP);
5397
5398 // Check to see if this gep only has a single variable index. If so, and if
5399 // any constant indices are a multiple of its scale, then we can compute this
5400 // in terms of the scale of the variable index. For example, if the GEP
5401 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5402 // because the expression will cross zero at the same point.
5403 unsigned i, e = GEP->getNumOperands();
5404 int64_t Offset = 0;
5405 for (i = 1; i != e; ++i, ++GTI) {
5406 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5407 // Compute the aggregate offset of constant indices.
5408 if (CI->isZero()) continue;
5409
5410 // Handle a struct index, which adds its field offset to the pointer.
5411 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5412 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5413 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005414 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005415 Offset += Size*CI->getSExtValue();
5416 }
5417 } else {
5418 // Found our variable index.
5419 break;
5420 }
5421 }
5422
5423 // If there are no variable indices, we must have a constant offset, just
5424 // evaluate it the general way.
5425 if (i == e) return 0;
5426
5427 Value *VariableIdx = GEP->getOperand(i);
5428 // Determine the scale factor of the variable element. For example, this is
5429 // 4 if the variable index is into an array of i32.
Duncan Sands777d2302009-05-09 07:06:46 +00005430 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005431
5432 // Verify that there are no other variable indices. If so, emit the hard way.
5433 for (++i, ++GTI; i != e; ++i, ++GTI) {
5434 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5435 if (!CI) return 0;
5436
5437 // Compute the aggregate offset of constant indices.
5438 if (CI->isZero()) continue;
5439
5440 // Handle a struct index, which adds its field offset to the pointer.
5441 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5442 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5443 } else {
Duncan Sands777d2302009-05-09 07:06:46 +00005444 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattner10c0d912008-04-22 02:53:33 +00005445 Offset += Size*CI->getSExtValue();
5446 }
5447 }
5448
5449 // Okay, we know we have a single variable index, which must be a
5450 // pointer/array/vector index. If there is no offset, life is simple, return
5451 // the index.
5452 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5453 if (Offset == 0) {
5454 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5455 // we don't need to bother extending: the extension won't affect where the
5456 // computation crosses zero.
5457 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
Owen Anderson1d0be152009-08-13 21:58:54 +00005458 VariableIdx = new TruncInst(VariableIdx,
5459 TD.getIntPtrType(VariableIdx->getContext()),
Daniel Dunbar460f6562009-07-26 09:48:23 +00005460 VariableIdx->getName(), &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005461 return VariableIdx;
5462 }
5463
5464 // Otherwise, there is an index. The computation we will do will be modulo
5465 // the pointer size, so get it.
5466 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5467
5468 Offset &= PtrSizeMask;
5469 VariableScale &= PtrSizeMask;
5470
5471 // To do this transformation, any constant index must be a multiple of the
5472 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5473 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5474 // multiple of the variable scale.
5475 int64_t NewOffs = Offset / (int64_t)VariableScale;
5476 if (Offset != NewOffs*(int64_t)VariableScale)
5477 return 0;
5478
5479 // Okay, we can do this evaluation. Start by converting the index to intptr.
Owen Anderson1d0be152009-08-13 21:58:54 +00005480 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
Chris Lattner10c0d912008-04-22 02:53:33 +00005481 if (VariableIdx->getType() != IntPtrTy)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005482 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattner10c0d912008-04-22 02:53:33 +00005483 true /*SExt*/,
Daniel Dunbar460f6562009-07-26 09:48:23 +00005484 VariableIdx->getName(), &I);
Owen Andersoneed707b2009-07-24 23:12:02 +00005485 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005486 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattner10c0d912008-04-22 02:53:33 +00005487}
5488
5489
Reid Spencere4d87aa2006-12-23 06:05:41 +00005490/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005491/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005492Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005493 ICmpInst::Predicate Cond,
5494 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005495 // Look through bitcasts.
5496 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5497 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005498
Chris Lattner574da9b2005-01-13 20:14:25 +00005499 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005500 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005501 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005502 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005503 // know pointers can't overflow since the gep is inbounds. See if we can
5504 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005505 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5506
5507 // If not, synthesize the offset the hard way.
5508 if (Offset == 0)
5509 Offset = EmitGEPOffset(GEPLHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005510 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005511 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005512 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005513 // If the base pointers are different, but the indices are the same, just
5514 // compare the base pointer.
5515 if (PtrBase != GEPRHS->getOperand(0)) {
5516 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005517 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005518 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005519 if (IndicesTheSame)
5520 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5521 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5522 IndicesTheSame = false;
5523 break;
5524 }
5525
5526 // If all indices are the same, just compare the base pointers.
5527 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005528 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005529 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005530
5531 // Otherwise, the base pointers are different and the indices are
5532 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005533 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005534 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005535
Chris Lattnere9d782b2005-01-13 22:25:21 +00005536 // If one of the GEPs has all zero indices, recurse.
5537 bool AllZeros = true;
5538 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5539 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5540 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5541 AllZeros = false;
5542 break;
5543 }
5544 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005545 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5546 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005547
5548 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005549 AllZeros = true;
5550 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5551 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5552 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5553 AllZeros = false;
5554 break;
5555 }
5556 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005557 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005558
Chris Lattner4401c9c2005-01-14 00:20:05 +00005559 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5560 // If the GEPs only differ by one index, compare it.
5561 unsigned NumDifferences = 0; // Keep track of # differences.
5562 unsigned DiffOperand = 0; // The operand that differs.
5563 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5564 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005565 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5566 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005567 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005568 NumDifferences = 2;
5569 break;
5570 } else {
5571 if (NumDifferences++) break;
5572 DiffOperand = i;
5573 }
5574 }
5575
5576 if (NumDifferences == 0) // SAME GEP?
5577 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005578 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005579 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005580
Chris Lattner4401c9c2005-01-14 00:20:05 +00005581 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005582 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5583 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005584 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005585 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005586 }
5587 }
5588
Reid Spencere4d87aa2006-12-23 06:05:41 +00005589 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005590 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005591 if (TD &&
5592 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005593 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5594 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5595 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5596 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005597 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005598 }
5599 }
5600 return 0;
5601}
5602
Chris Lattnera5406232008-05-19 20:18:56 +00005603/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5604///
5605Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5606 Instruction *LHSI,
5607 Constant *RHSC) {
5608 if (!isa<ConstantFP>(RHSC)) return 0;
5609 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5610
5611 // Get the width of the mantissa. We don't want to hack on conversions that
5612 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005613 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005614 if (MantissaWidth == -1) return 0; // Unknown.
5615
5616 // Check to see that the input is converted from an integer type that is small
5617 // enough that preserves all bits. TODO: check here for "known" sign bits.
5618 // 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 +00005619 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005620
5621 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005622 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5623 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005624 ++InputSize;
5625
5626 // If the conversion would lose info, don't hack on this.
5627 if ((int)InputSize > MantissaWidth)
5628 return 0;
5629
5630 // Otherwise, we can potentially simplify the comparison. We know that it
5631 // will always come through as an integer value and we know the constant is
5632 // not a NAN (it would have been previously simplified).
5633 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5634
5635 ICmpInst::Predicate Pred;
5636 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005637 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005638 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005639 case FCmpInst::FCMP_OEQ:
5640 Pred = ICmpInst::ICMP_EQ;
5641 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005642 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005643 case FCmpInst::FCMP_OGT:
5644 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5645 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005646 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005647 case FCmpInst::FCMP_OGE:
5648 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5649 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005650 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005651 case FCmpInst::FCMP_OLT:
5652 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5653 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005654 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005655 case FCmpInst::FCMP_OLE:
5656 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5657 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005658 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005659 case FCmpInst::FCMP_ONE:
5660 Pred = ICmpInst::ICMP_NE;
5661 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005662 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005663 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005664 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005665 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005666 }
5667
5668 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5669
5670 // Now we know that the APFloat is a normal number, zero or inf.
5671
Chris Lattner85162782008-05-20 03:50:52 +00005672 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005673 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005674 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005675
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005676 if (!LHSUnsigned) {
5677 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5678 // and large values.
5679 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5680 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5681 APFloat::rmNearestTiesToEven);
5682 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5683 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5684 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005685 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5686 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005687 }
5688 } else {
5689 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5690 // +INF and large values.
5691 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5692 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5693 APFloat::rmNearestTiesToEven);
5694 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5695 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5696 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005697 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5698 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005699 }
Chris Lattnera5406232008-05-19 20:18:56 +00005700 }
5701
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005702 if (!LHSUnsigned) {
5703 // See if the RHS value is < SignedMin.
5704 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5705 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5706 APFloat::rmNearestTiesToEven);
5707 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5708 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5709 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005710 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5711 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005712 }
Chris Lattnera5406232008-05-19 20:18:56 +00005713 }
5714
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005715 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5716 // [0, UMAX], but it may still be fractional. See if it is fractional by
5717 // casting the FP value to the integer value and back, checking for equality.
5718 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005719 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005720 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5721 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005722 if (!RHS.isZero()) {
5723 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005724 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5725 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005726 if (!Equal) {
5727 // If we had a comparison against a fractional value, we have to adjust
5728 // the compare predicate and sometimes the value. RHSC is rounded towards
5729 // zero at this point.
5730 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005731 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005732 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005733 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005734 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005735 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005736 case ICmpInst::ICMP_ULE:
5737 // (float)int <= 4.4 --> int <= 4
5738 // (float)int <= -4.4 --> false
5739 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005740 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005741 break;
5742 case ICmpInst::ICMP_SLE:
5743 // (float)int <= 4.4 --> int <= 4
5744 // (float)int <= -4.4 --> int < -4
5745 if (RHS.isNegative())
5746 Pred = ICmpInst::ICMP_SLT;
5747 break;
5748 case ICmpInst::ICMP_ULT:
5749 // (float)int < -4.4 --> false
5750 // (float)int < 4.4 --> int <= 4
5751 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005752 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005753 Pred = ICmpInst::ICMP_ULE;
5754 break;
5755 case ICmpInst::ICMP_SLT:
5756 // (float)int < -4.4 --> int < -4
5757 // (float)int < 4.4 --> int <= 4
5758 if (!RHS.isNegative())
5759 Pred = ICmpInst::ICMP_SLE;
5760 break;
5761 case ICmpInst::ICMP_UGT:
5762 // (float)int > 4.4 --> int > 4
5763 // (float)int > -4.4 --> true
5764 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005765 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005766 break;
5767 case ICmpInst::ICMP_SGT:
5768 // (float)int > 4.4 --> int > 4
5769 // (float)int > -4.4 --> int >= -4
5770 if (RHS.isNegative())
5771 Pred = ICmpInst::ICMP_SGE;
5772 break;
5773 case ICmpInst::ICMP_UGE:
5774 // (float)int >= -4.4 --> true
5775 // (float)int >= 4.4 --> int > 4
5776 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005777 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005778 Pred = ICmpInst::ICMP_UGT;
5779 break;
5780 case ICmpInst::ICMP_SGE:
5781 // (float)int >= -4.4 --> int >= -4
5782 // (float)int >= 4.4 --> int > 4
5783 if (!RHS.isNegative())
5784 Pred = ICmpInst::ICMP_SGT;
5785 break;
5786 }
Chris Lattnera5406232008-05-19 20:18:56 +00005787 }
5788 }
5789
5790 // Lower this FP comparison into an appropriate integer version of the
5791 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005792 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005793}
5794
Reid Spencere4d87aa2006-12-23 06:05:41 +00005795Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5796 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00005797 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005798
Chris Lattner58e97462007-01-14 19:42:17 +00005799 // Fold trivial predicates.
5800 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005801 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005802 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005803 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005804
5805 // Simplify 'fcmp pred X, X'
5806 if (Op0 == Op1) {
5807 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005808 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00005809 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5810 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5811 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson5defacc2009-07-31 17:39:07 +00005812 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005813 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5814 case FCmpInst::FCMP_OLT: // True if ordered and less than
5815 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson5defacc2009-07-31 17:39:07 +00005816 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner58e97462007-01-14 19:42:17 +00005817
5818 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5819 case FCmpInst::FCMP_ULT: // True if unordered or less than
5820 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5821 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5822 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5823 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00005824 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005825 return &I;
5826
5827 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5828 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5829 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5830 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5831 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5832 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00005833 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00005834 return &I;
5835 }
5836 }
5837
Reid Spencere4d87aa2006-12-23 06:05:41 +00005838 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005839 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Chris Lattnere87597f2004-10-16 18:11:37 +00005840
Reid Spencere4d87aa2006-12-23 06:05:41 +00005841 // Handle fcmp with constant RHS
5842 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnera5406232008-05-19 20:18:56 +00005843 // If the constant is a nan, see if we can fold the comparison based on it.
5844 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5845 if (CFP->getValueAPF().isNaN()) {
5846 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson5defacc2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner85162782008-05-20 03:50:52 +00005848 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5849 "Comparison must be either ordered or unordered!");
5850 // True if unordered.
Owen Anderson5defacc2009-07-31 17:39:07 +00005851 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005852 }
5853 }
5854
Reid Spencere4d87aa2006-12-23 06:05:41 +00005855 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5856 switch (LHSI->getOpcode()) {
5857 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00005858 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5859 // block. If in the same block, we're encouraging jump threading. If
5860 // not, we are just pessimizing the code by making an i1 phi.
5861 if (LHSI->getParent() == I.getParent())
5862 if (Instruction *NV = FoldOpIntoPhi(I))
5863 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005864 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005865 case Instruction::SIToFP:
5866 case Instruction::UIToFP:
5867 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5868 return NV;
5869 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005870 case Instruction::Select:
5871 // If either operand of the select is a constant, we can fold the
5872 // comparison into the select arms, which will cause one to be
5873 // constant folded and the select turned into a bitwise or.
5874 Value *Op1 = 0, *Op2 = 0;
5875 if (LHSI->hasOneUse()) {
5876 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5877 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005878 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005879 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005880 Op2 = Builder->CreateFCmp(I.getPredicate(),
5881 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005882 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5883 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005884 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005885 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00005886 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5887 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 }
5889 }
5890
5891 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00005892 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005893 break;
5894 }
5895 }
5896
5897 return Changed ? &I : 0;
5898}
5899
5900Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5901 bool Changed = SimplifyCompare(I);
5902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5903 const Type *Ty = Op0->getType();
5904
5905 // icmp X, X
5906 if (Op0 == Op1)
Owen Anderson1d0be152009-08-13 21:58:54 +00005907 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005908 I.isTrueWhenEqual()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00005909
5910 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson1d0be152009-08-13 21:58:54 +00005911 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00005912
Reid Spencere4d87aa2006-12-23 06:05:41 +00005913 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00005914 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00005915 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5916 isa<ConstantPointerNull>(Op0)) &&
5917 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00005918 isa<ConstantPointerNull>(Op1)))
Owen Anderson1d0be152009-08-13 21:58:54 +00005919 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005920 !I.isTrueWhenEqual()));
Chris Lattner8b170942002-08-09 23:47:40 +00005921
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00005923 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005924 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005925 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005926 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00005927 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00005928 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00005929 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005930 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005931 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00005932
Reid Spencere4d87aa2006-12-23 06:05:41 +00005933 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00005934 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00005935 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005936 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00005937 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005938 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005939 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005940 case ICmpInst::ICMP_SGT:
5941 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00005942 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00005943 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00005944 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005945 return BinaryOperator::CreateAnd(Not, Op0);
5946 }
5947 case ICmpInst::ICMP_UGE:
5948 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5949 // FALL THROUGH
5950 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00005951 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005952 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00005953 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00005954 case ICmpInst::ICMP_SGE:
5955 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5956 // FALL THROUGH
5957 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00005958 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00005959 return BinaryOperator::CreateOr(Not, Op0);
5960 }
Chris Lattner5dbef222004-08-11 00:50:51 +00005961 }
Chris Lattner8b170942002-08-09 23:47:40 +00005962 }
5963
Dan Gohman1c8491e2009-04-25 17:12:48 +00005964 unsigned BitWidth = 0;
5965 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00005966 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5967 else if (Ty->isIntOrIntVector())
5968 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00005969
5970 bool isSignBit = false;
5971
Dan Gohman81b28ce2008-09-16 18:46:06 +00005972 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00005973 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00005974 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00005975
Chris Lattnerb6566012008-01-05 01:18:20 +00005976 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5977 if (I.isEquality() && CI->isNullValue() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005978 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00005979 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005980 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00005981 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00005982
Dan Gohman81b28ce2008-09-16 18:46:06 +00005983 // If we have an icmp le or icmp ge instruction, turn it into the
5984 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5985 // them being folded in the code below.
Chris Lattner84dff672008-07-11 05:08:55 +00005986 switch (I.getPredicate()) {
5987 default: break;
5988 case ICmpInst::ICMP_ULE:
5989 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005990 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005991 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005992 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005993 case ICmpInst::ICMP_SLE:
5994 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00005995 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005996 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00005997 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00005998 case ICmpInst::ICMP_UGE:
5999 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006000 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006001 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006002 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006003 case ICmpInst::ICMP_SGE:
6004 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson5defacc2009-07-31 17:39:07 +00006005 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006006 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006007 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006008 }
6009
Chris Lattner183661e2008-07-11 05:40:05 +00006010 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006011 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006012 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006013 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6014 }
6015
6016 // See if we can fold the comparison based on range information we can get
6017 // by checking whether bits are known to be zero or one in the input.
6018 if (BitWidth != 0) {
6019 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6020 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6021
6022 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006023 isSignBit ? APInt::getSignBit(BitWidth)
6024 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006025 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006026 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006027 if (SimplifyDemandedBits(I.getOperandUse(1),
6028 APInt::getAllOnesValue(BitWidth),
6029 Op1KnownZero, Op1KnownOne, 0))
6030 return &I;
6031
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006032 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006033 // in. Compute the Min, Max and RHS values based on the known bits. For the
6034 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006035 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6036 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6037 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6038 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6039 Op0Min, Op0Max);
6040 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6041 Op1Min, Op1Max);
6042 } else {
6043 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6044 Op0Min, Op0Max);
6045 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6046 Op1Min, Op1Max);
6047 }
6048
Chris Lattner183661e2008-07-11 05:40:05 +00006049 // If Min and Max are known to be the same, then SimplifyDemandedBits
6050 // figured out that the LHS is a constant. Just constant fold this now so
6051 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006052 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006053 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006054 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006055 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006056 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006057 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006058
Chris Lattner183661e2008-07-11 05:40:05 +00006059 // Based on the range information we know about the LHS, see if we can
6060 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006061 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006062 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006063 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006064 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006065 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006066 break;
6067 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006068 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006069 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006070 break;
6071 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006072 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006073 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006074 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006075 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006076 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006077 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006078 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6079 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006080 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006081 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006082
6083 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6084 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006085 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006086 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006087 }
Chris Lattner84dff672008-07-11 05:08:55 +00006088 break;
6089 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006090 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006092 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006093 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006094
6095 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006096 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006097 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6098 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006099 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006100 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006101
6102 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6103 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006104 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006105 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006106 }
Chris Lattner84dff672008-07-11 05:08:55 +00006107 break;
6108 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006109 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006110 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006111 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006112 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006113 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006114 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006115 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6116 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006117 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006118 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006119 }
Chris Lattner84dff672008-07-11 05:08:55 +00006120 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006121 case ICmpInst::ICMP_SGT:
6122 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006123 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006124 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006125 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006126
6127 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006128 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006129 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6130 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006131 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006132 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006133 }
6134 break;
6135 case ICmpInst::ICMP_SGE:
6136 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6137 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006138 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006139 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006140 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006141 break;
6142 case ICmpInst::ICMP_SLE:
6143 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6144 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006145 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006146 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006147 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006148 break;
6149 case ICmpInst::ICMP_UGE:
6150 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6151 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006152 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006153 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006154 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006155 break;
6156 case ICmpInst::ICMP_ULE:
6157 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6158 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006159 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006160 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006162 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006163 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006164
6165 // Turn a signed comparison into an unsigned one if both operands
6166 // are known to have the same sign.
6167 if (I.isSignedPredicate() &&
6168 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6169 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006170 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006171 }
6172
6173 // Test if the ICmpInst instruction is used exclusively by a select as
6174 // part of a minimum or maximum operation. If so, refrain from doing
6175 // any other folding. This helps out other analyses which understand
6176 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6177 // and CodeGen. And in this case, at least one of the comparison
6178 // operands has at least one user besides the compare (the select),
6179 // which would often largely negate the benefit of folding anyway.
6180 if (I.hasOneUse())
6181 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6182 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6183 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6184 return 0;
6185
6186 // See if we are doing a comparison between a constant and an instruction that
6187 // can be folded into the comparison.
6188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006189 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006190 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006191 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006192 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006193 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6194 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006195 }
6196
Chris Lattner01deb9d2007-04-03 17:43:25 +00006197 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006198 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6199 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6200 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006201 case Instruction::GetElementPtr:
6202 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006203 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00006204 bool isAllZeros = true;
6205 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6206 if (!isa<Constant>(LHSI->getOperand(i)) ||
6207 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6208 isAllZeros = false;
6209 break;
6210 }
6211 if (isAllZeros)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006212 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Owen Andersona7235ea2009-07-31 20:28:14 +00006213 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006214 }
6215 break;
6216
Chris Lattner6970b662005-04-23 15:31:55 +00006217 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006218 // Only fold icmp into the PHI if the phi and fcmp are in the same
6219 // block. If in the same block, we're encouraging jump threading. If
6220 // not, we are just pessimizing the code by making an i1 phi.
6221 if (LHSI->getParent() == I.getParent())
6222 if (Instruction *NV = FoldOpIntoPhi(I))
6223 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006224 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006225 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006226 // If either operand of the select is a constant, we can fold the
6227 // comparison into the select arms, which will cause one to be
6228 // constant folded and the select turned into a bitwise or.
6229 Value *Op1 = 0, *Op2 = 0;
6230 if (LHSI->hasOneUse()) {
6231 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6232 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006233 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006234 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006235 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6236 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006237 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6238 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006239 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006240 // Insert a new ICmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006241 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6242 RHSC, I.getName());
Chris Lattner6970b662005-04-23 15:31:55 +00006243 }
6244 }
Jeff Cohen9d809302005-04-23 21:38:35 +00006245
Chris Lattner6970b662005-04-23 15:31:55 +00006246 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006247 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Chris Lattner6970b662005-04-23 15:31:55 +00006248 break;
6249 }
Chris Lattner4802d902007-04-06 18:57:34 +00006250 case Instruction::Malloc:
6251 // If we have (malloc != null), and if the malloc has a single use, we
6252 // can assume it is successful and remove the malloc.
6253 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00006254 Worklist.Add(LHSI);
Owen Anderson1d0be152009-08-13 21:58:54 +00006255 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00006256 !I.isTrueWhenEqual()));
Chris Lattner4802d902007-04-06 18:57:34 +00006257 }
6258 break;
6259 }
Chris Lattner6970b662005-04-23 15:31:55 +00006260 }
6261
Reid Spencere4d87aa2006-12-23 06:05:41 +00006262 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006263 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006264 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006265 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006266 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006267 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6268 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006269 return NI;
6270
Reid Spencere4d87aa2006-12-23 06:05:41 +00006271 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006272 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6273 // now.
6274 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6275 if (isa<PointerType>(Op0->getType()) &&
6276 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006277 // We keep moving the cast from the left operand over to the right
6278 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006279 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006280
Chris Lattner57d86372007-01-06 01:45:59 +00006281 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6282 // so eliminate it as well.
6283 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6284 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006285
Chris Lattnerde90b762003-11-03 04:25:02 +00006286 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006287 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006288 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006289 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006290 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006291 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00006292 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00006293 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006294 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006295 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006296 }
Chris Lattner57d86372007-01-06 01:45:59 +00006297 }
6298
6299 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006300 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006301 // This comes up when you have code like
6302 // int X = A < B;
6303 // if (X) ...
6304 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006305 // with a constant or another cast from the same type.
6306 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006307 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006308 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006309 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006310
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006311 // See if it's the same type of instruction on the left and right.
6312 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6313 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006314 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006315 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006316 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006317 default: break;
6318 case Instruction::Add:
6319 case Instruction::Sub:
6320 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006321 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006322 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006323 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006324 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6326 if (CI->getValue().isSignBit()) {
6327 ICmpInst::Predicate Pred = I.isSignedPredicate()
6328 ? I.getUnsignedPredicate()
6329 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006330 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006331 Op1I->getOperand(0));
6332 }
6333
6334 if (CI->getValue().isMaxSignedValue()) {
6335 ICmpInst::Predicate Pred = I.isSignedPredicate()
6336 ? I.getUnsignedPredicate()
6337 : I.getSignedPredicate();
6338 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006339 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006340 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006341 }
6342 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006343 break;
6344 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006345 if (!I.isEquality())
6346 break;
6347
Nick Lewycky5d52c452008-08-21 05:56:10 +00006348 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6349 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6350 // Mask = -1 >> count-trailing-zeros(Cst).
6351 if (!CI->isZero() && !CI->isOne()) {
6352 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006353 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006354 APInt::getLowBitsSet(AP.getBitWidth(),
6355 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006356 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006357 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6358 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006359 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006360 }
6361 }
6362 break;
6363 }
6364 }
6365 }
6366 }
6367
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006368 // ~x < ~y --> y < x
6369 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006370 if (match(Op0, m_Not(m_Value(A))) &&
6371 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006372 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006373 }
6374
Chris Lattner65b72ba2006-09-18 04:22:48 +00006375 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006376 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006377
6378 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006379 if (match(Op0, m_Neg(m_Value(A))) &&
6380 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006381 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006382
Dan Gohman4ae51262009-08-12 16:23:25 +00006383 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006384 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6385 Value *OtherVal = A == Op1 ? 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 }
6389
Dan Gohman4ae51262009-08-12 16:23:25 +00006390 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006391 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006392 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006393 if (match(B, m_ConstantInt(C1)) &&
6394 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006395 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006396 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006397 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6398 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006399 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006400
6401 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006402 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6403 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6404 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6405 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006406 }
6407 }
6408
Dan Gohman4ae51262009-08-12 16:23:25 +00006409 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006410 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006411 // A == (A^B) -> B == 0
6412 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006413 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006414 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006415 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006416
6417 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006418 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006419 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006420 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006421
6422 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006423 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006424 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006425 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006426
Chris Lattner9c2328e2006-11-14 06:06:06 +00006427 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6428 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006429 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6430 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006431 Value *X = 0, *Y = 0, *Z = 0;
6432
6433 if (A == C) {
6434 X = B; Y = D; Z = A;
6435 } else if (A == D) {
6436 X = B; Y = C; Z = A;
6437 } else if (B == C) {
6438 X = A; Y = D; Z = B;
6439 } else if (B == D) {
6440 X = A; Y = C; Z = B;
6441 }
6442
6443 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006444 Op1 = Builder->CreateXor(X, Y, "tmp");
6445 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006446 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006447 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006448 return &I;
6449 }
6450 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006451 }
Chris Lattner7e708292002-06-25 16:13:24 +00006452 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006453}
6454
Chris Lattner562ef782007-06-20 23:46:26 +00006455
6456/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6457/// and CmpRHS are both known to be integer constants.
6458Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6459 ConstantInt *DivRHS) {
6460 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6461 const APInt &CmpRHSV = CmpRHS->getValue();
6462
6463 // FIXME: If the operand types don't match the type of the divide
6464 // then don't attempt this transform. The code below doesn't have the
6465 // logic to deal with a signed divide and an unsigned compare (and
6466 // vice versa). This is because (x /s C1) <s C2 produces different
6467 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6468 // (x /u C1) <u C2. Simply casting the operands and result won't
6469 // work. :( The if statement below tests that condition and bails
6470 // if it finds it.
6471 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6472 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6473 return 0;
6474 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00006475 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00006476 if (DivIsSigned && DivRHS->isAllOnesValue())
6477 return 0; // The overflow computation also screws up here
6478 if (DivRHS->isOne())
6479 return 0; // Not worth bothering, and eliminates some funny cases
6480 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00006481
6482 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6483 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6484 // C2 (CI). By solving for X we can turn this into a range check
6485 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006486 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00006487
6488 // Determine if the product overflows by seeing if the product is
6489 // not equal to the divide. Make sure we do the same kind of divide
6490 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006491 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6492 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00006493
6494 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00006495 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00006496
Chris Lattner1dbfd482007-06-21 18:11:19 +00006497 // Figure out the interval that is being checked. For example, a comparison
6498 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6499 // Compute this interval based on the constants involved and the signedness of
6500 // the compare/divide. This computes a half-open interval, keeping track of
6501 // whether either value in the interval overflows. After analysis each
6502 // overflow variable is set to 0 if it's corresponding bound variable is valid
6503 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6504 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00006505 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006506
Chris Lattner562ef782007-06-20 23:46:26 +00006507 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00006508 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00006509 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00006510 HiOverflow = LoOverflow = ProdOV;
6511 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006512 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00006513 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006514 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006515 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00006516 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00006517 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00006518 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006519 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6520 HiOverflow = LoOverflow = ProdOV;
6521 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006522 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006523 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00006524 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006525 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00006526 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6527 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006528 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006529 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00006530 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00006531 true) ? -1 : 0;
6532 }
Chris Lattner562ef782007-06-20 23:46:26 +00006533 }
Dan Gohman76491272008-02-13 22:09:18 +00006534 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00006535 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00006536 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00006537 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00006538 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006539 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6540 HiOverflow = 1; // [INTMIN+1, overflow)
6541 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6542 }
Dan Gohman76491272008-02-13 22:09:18 +00006543 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00006544 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00006545 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006546 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006547 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006548 LoOverflow = AddWithOverflow(LoBound, HiBound,
6549 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00006550 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00006551 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6552 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00006553 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00006554 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00006555 }
6556
Chris Lattner1dbfd482007-06-21 18:11:19 +00006557 // Dividing by a negative swaps the condition. LT <-> GT
6558 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00006559 }
6560
6561 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00006562 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006563 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00006564 case ICmpInst::ICMP_EQ:
6565 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006566 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006567 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006568 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006569 ICmpInst::ICMP_UGE, X, LoBound);
6570 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006571 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006572 ICmpInst::ICMP_ULT, X, HiBound);
6573 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006574 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006575 case ICmpInst::ICMP_NE:
6576 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00006577 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00006578 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006579 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00006580 ICmpInst::ICMP_ULT, X, LoBound);
6581 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006582 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00006583 ICmpInst::ICMP_UGE, X, HiBound);
6584 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00006585 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00006586 case ICmpInst::ICMP_ULT:
6587 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006588 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006589 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006590 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006591 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006592 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006593 case ICmpInst::ICMP_UGT:
6594 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00006595 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006596 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006597 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00006598 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00006599 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006600 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006601 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006602 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00006603 }
6604}
6605
6606
Chris Lattner01deb9d2007-04-03 17:43:25 +00006607/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6608///
6609Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6610 Instruction *LHSI,
6611 ConstantInt *RHS) {
6612 const APInt &RHSV = RHS->getValue();
6613
6614 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00006615 case Instruction::Trunc:
6616 if (ICI.isEquality() && LHSI->hasOneUse()) {
6617 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6618 // of the high bits truncated out of x are known.
6619 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6620 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6621 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6622 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6623 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6624
6625 // If all the high bits are known, we can do this xform.
6626 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6627 // Pull in the high bits from known-ones set.
6628 APInt NewRHS(RHS->getValue());
6629 NewRHS.zext(SrcBits);
6630 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006631 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006632 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00006633 }
6634 }
6635 break;
6636
Duncan Sands0091bf22007-04-04 06:42:45 +00006637 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00006638 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6639 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6640 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006641 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6642 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006643 Value *CompareVal = LHSI->getOperand(0);
6644
6645 // If the sign bit of the XorCST is not set, there is no change to
6646 // the operation, just stop using the Xor.
6647 if (!XorCST->getValue().isNegative()) {
6648 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00006649 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006650 return &ICI;
6651 }
6652
6653 // Was the old condition true if the operand is positive?
6654 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6655
6656 // If so, the new one isn't.
6657 isTrueIfPositive ^= true;
6658
6659 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006660 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006661 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006662 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006663 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00006664 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006665 }
Nick Lewycky4333f492009-01-31 21:30:05 +00006666
6667 if (LHSI->hasOneUse()) {
6668 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6669 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6670 const APInt &SignBit = XorCST->getValue();
6671 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6672 ? ICI.getUnsignedPredicate()
6673 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006674 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006675 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006676 }
6677
6678 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006679 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00006680 const APInt &NotSignBit = XorCST->getValue();
6681 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6682 ? ICI.getUnsignedPredicate()
6683 : ICI.getSignedPredicate();
6684 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006685 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006686 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00006687 }
6688 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006689 }
6690 break;
6691 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6692 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6693 LHSI->getOperand(0)->hasOneUse()) {
6694 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6695
6696 // If the LHS is an AND of a truncating cast, we can widen the
6697 // and/compare to be the input width without changing the value
6698 // produced, eliminating a cast.
6699 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6700 // We can do this transformation if either the AND constant does not
6701 // have its sign bit set or if it is an equality comparison.
6702 // Extending a relational comparison when we're checking the sign
6703 // bit would not work.
6704 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00006705 (ICI.isEquality() ||
6706 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006707 uint32_t BitWidth =
6708 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6709 APInt NewCST = AndCST->getValue();
6710 NewCST.zext(BitWidth);
6711 APInt NewCI = RHSV;
6712 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00006713 Value *NewAnd =
6714 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006715 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006716 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00006717 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006718 }
6719 }
6720
6721 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6722 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6723 // happens a LOT in code produced by the C front-end, for bitfield
6724 // access.
6725 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6726 if (Shift && !Shift->isShift())
6727 Shift = 0;
6728
6729 ConstantInt *ShAmt;
6730 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6731 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6732 const Type *AndTy = AndCST->getType(); // Type of the and.
6733
6734 // We can fold this as long as we can't shift unknown bits
6735 // into the mask. This can only happen with signed shift
6736 // rights, as they sign-extend.
6737 if (ShAmt) {
6738 bool CanFold = Shift->isLogicalShift();
6739 if (!CanFold) {
6740 // To test for the bad case of the signed shr, see if any
6741 // of the bits shifted in could be tested after the mask.
6742 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6743 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6744
6745 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6746 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6747 AndCST->getValue()) == 0)
6748 CanFold = true;
6749 }
6750
6751 if (CanFold) {
6752 Constant *NewCst;
6753 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006754 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006755 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006756 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006757
6758 // Check to see if we are shifting out any of the bits being
6759 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006760 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00006761 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006762 // If we shifted bits out, the fold is not going to work out.
6763 // As a special case, check to see if this means that the
6764 // result is always true or false now.
6765 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00006766 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006767 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00006768 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006769 } else {
6770 ICI.setOperand(1, NewCst);
6771 Constant *NewAndCST;
6772 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00006773 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006774 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00006775 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006776 LHSI->setOperand(1, NewAndCST);
6777 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00006778 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00006779 return &ICI;
6780 }
6781 }
6782 }
6783
6784 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6785 // preferable because it allows the C<<Y expression to be hoisted out
6786 // of a loop if Y is invariant and X is not.
6787 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00006788 ICI.isEquality() && !Shift->isArithmeticShift() &&
6789 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00006790 // Compute C << Y.
6791 Value *NS;
6792 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00006793 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006794 } else {
6795 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00006796 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00006797 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006798
6799 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00006800 Value *NewAnd =
6801 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00006802
6803 ICI.setOperand(0, NewAnd);
6804 return &ICI;
6805 }
6806 }
6807 break;
6808
Chris Lattnera0141b92007-07-15 20:42:37 +00006809 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6810 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6811 if (!ShAmt) break;
6812
6813 uint32_t TypeBits = RHSV.getBitWidth();
6814
6815 // Check that the shift amount is in range. If not, don't perform
6816 // undefined shifts. When the shift is visited it will be
6817 // simplified.
6818 if (ShAmt->uge(TypeBits))
6819 break;
6820
6821 if (ICI.isEquality()) {
6822 // If we are comparing against bits always shifted out, the
6823 // comparison cannot succeed.
6824 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00006825 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00006826 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00006827 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6828 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006829 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00006830 return ReplaceInstUsesWith(ICI, Cst);
6831 }
6832
6833 if (LHSI->hasOneUse()) {
6834 // Otherwise strength reduce the shift into an and.
6835 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6836 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00006837 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00006838 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006839
Chris Lattner74381062009-08-30 07:44:24 +00006840 Value *And =
6841 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006842 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00006843 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006844 }
6845 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006846
6847 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6848 bool TrueIfSigned = false;
6849 if (LHSI->hasOneUse() &&
6850 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6851 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00006852 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00006853 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00006854 Value *And =
6855 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006856 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00006857 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00006858 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006859 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006860 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006861
6862 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00006863 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006864 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00006865 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006866 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006867
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006868 // Check that the shift amount is in range. If not, don't perform
6869 // undefined shifts. When the shift is visited it will be
6870 // simplified.
6871 uint32_t TypeBits = RHSV.getBitWidth();
6872 if (ShAmt->uge(TypeBits))
6873 break;
6874
6875 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00006876
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006877 // If we are comparing against bits always shifted out, the
6878 // comparison cannot succeed.
6879 APInt Comp = RHSV << ShAmtVal;
6880 if (LHSI->getOpcode() == Instruction::LShr)
6881 Comp = Comp.lshr(ShAmtVal);
6882 else
6883 Comp = Comp.ashr(ShAmtVal);
6884
6885 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6886 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00006887 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006888 return ReplaceInstUsesWith(ICI, Cst);
6889 }
6890
6891 // Otherwise, check to see if the bits shifted out are known to be zero.
6892 // If so, we can compare against the unshifted value:
6893 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00006894 if (LHSI->hasOneUse() &&
6895 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006896 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006897 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006898 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006899 }
Chris Lattnera0141b92007-07-15 20:42:37 +00006900
Evan Chengf30752c2008-04-23 00:38:06 +00006901 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00006902 // Otherwise strength reduce the shift into an and.
6903 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00006904 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00006905
Chris Lattner74381062009-08-30 07:44:24 +00006906 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6907 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006908 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00006909 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006910 }
6911 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00006912 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00006913
6914 case Instruction::SDiv:
6915 case Instruction::UDiv:
6916 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6917 // Fold this div into the comparison, producing a range check.
6918 // Determine, based on the divide type, what the range is being
6919 // checked. If there is an overflow on the low or high side, remember
6920 // it, otherwise compute the range [low, hi) bounding the new value.
6921 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00006922 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6923 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6924 DivRHS))
6925 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006926 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00006927
6928 case Instruction::Add:
6929 // Fold: icmp pred (add, X, C1), C2
6930
6931 if (!ICI.isEquality()) {
6932 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6933 if (!LHSC) break;
6934 const APInt &LHSV = LHSC->getValue();
6935
6936 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6937 .subtract(LHSV);
6938
6939 if (ICI.isSignedPredicate()) {
6940 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006941 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006942 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006943 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006944 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006945 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006946 }
6947 } else {
6948 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006949 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006950 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006951 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006952 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00006953 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00006954 }
6955 }
6956 }
6957 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00006958 }
6959
6960 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6961 if (ICI.isEquality()) {
6962 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6963
6964 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6965 // the second operand is a constant, simplify a bit.
6966 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6967 switch (BO->getOpcode()) {
6968 case Instruction::SRem:
6969 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6970 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6971 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6972 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00006973 Value *NewRem =
6974 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6975 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006976 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00006977 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006978 }
6979 }
6980 break;
6981 case Instruction::Add:
6982 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6983 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6984 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006985 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00006986 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00006987 } else if (RHSV == 0) {
6988 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6989 // efficiently invertible, or if the add has just this one use.
6990 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6991
Dan Gohman186a6362009-08-12 16:04:34 +00006992 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006993 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00006994 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006995 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006996 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00006997 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00006998 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006999 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007000 }
7001 }
7002 break;
7003 case Instruction::Xor:
7004 // For the xor case, we can xor two constants together, eliminating
7005 // the explicit xor.
7006 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007007 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007008 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007009
7010 // FALLTHROUGH
7011 case Instruction::Sub:
7012 // Replace (([sub|xor] A, B) != 0) with (A != B)
7013 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007014 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007015 BO->getOperand(1));
7016 break;
7017
7018 case Instruction::Or:
7019 // If bits are being or'd in that are not present in the constant we
7020 // are comparing against, then the comparison could never succeed!
7021 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007022 Constant *NotCI = ConstantExpr::getNot(RHS);
7023 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007024 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007025 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007026 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007027 }
7028 break;
7029
7030 case Instruction::And:
7031 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7032 // If bits are being compared against that are and'd out, then the
7033 // comparison can never succeed!
7034 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007035 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007036 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007037 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007038
7039 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7040 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007041 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007042 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007043 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007044
7045 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007046 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007047 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007048 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007049 ICmpInst::Predicate pred = isICMP_NE ?
7050 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007051 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007052 }
7053
7054 // ((X & ~7) == 0) --> X < 8
7055 if (RHSV == 0 && isHighOnes(BOC)) {
7056 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007057 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007058 ICmpInst::Predicate pred = isICMP_NE ?
7059 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007060 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007061 }
7062 }
7063 default: break;
7064 }
7065 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7066 // Handle icmp {eq|ne} <intrinsic>, intcst.
7067 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007068 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007069 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007070 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007071 return &ICI;
7072 }
7073 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007074 }
7075 return 0;
7076}
7077
7078/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7079/// We only handle extending casts so far.
7080///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007081Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7082 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007083 Value *LHSCIOp = LHSCI->getOperand(0);
7084 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007085 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007086 Value *RHSCIOp;
7087
Chris Lattner8c756c12007-05-05 22:41:33 +00007088 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7089 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007090 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7091 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007092 cast<IntegerType>(DestTy)->getBitWidth()) {
7093 Value *RHSOp = 0;
7094 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007095 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007096 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7097 RHSOp = RHSC->getOperand(0);
7098 // If the pointer types don't match, insert a bitcast.
7099 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00007100 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00007101 }
7102
7103 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007104 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007105 }
7106
7107 // The code below only handles extension cast instructions, so far.
7108 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007109 if (LHSCI->getOpcode() != Instruction::ZExt &&
7110 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007111 return 0;
7112
Reid Spencere4d87aa2006-12-23 06:05:41 +00007113 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7114 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007115
Reid Spencere4d87aa2006-12-23 06:05:41 +00007116 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007117 // Not an extension from the same type?
7118 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007119 if (RHSCIOp->getType() != LHSCIOp->getType())
7120 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007121
Nick Lewycky4189a532008-01-28 03:48:02 +00007122 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007123 // and the other is a zext), then we can't handle this.
7124 if (CI->getOpcode() != LHSCI->getOpcode())
7125 return 0;
7126
Nick Lewycky4189a532008-01-28 03:48:02 +00007127 // Deal with equality cases early.
7128 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007129 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007130
7131 // A signed comparison of sign extended values simplifies into a
7132 // signed comparison.
7133 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007134 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007135
7136 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007137 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007138 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007139
Reid Spencere4d87aa2006-12-23 06:05:41 +00007140 // If we aren't dealing with a constant on the RHS, exit early
7141 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7142 if (!CI)
7143 return 0;
7144
7145 // Compute the constant that would happen if we truncated to SrcTy then
7146 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007147 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7148 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007149 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007150
7151 // If the re-extended constant didn't change...
7152 if (Res2 == CI) {
7153 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7154 // For example, we might have:
Dan Gohmana119de82009-06-14 23:30:43 +00007155 // %A = sext i16 %X to i32
7156 // %B = icmp ugt i32 %A, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007157 // It is incorrect to transform this into
Dan Gohmana119de82009-06-14 23:30:43 +00007158 // %B = icmp ugt i16 %X, 1330
Reid Spencere4d87aa2006-12-23 06:05:41 +00007159 // because %A may have negative value.
7160 //
Chris Lattnerf2991842008-07-11 04:09:09 +00007161 // However, we allow this when the compare is EQ/NE, because they are
7162 // signless.
7163 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007164 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattnerf2991842008-07-11 04:09:09 +00007165 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00007166 }
7167
7168 // The re-extended constant changed so the constant cannot be represented
7169 // in the shorter type. Consequently, we cannot emit a simple comparison.
7170
7171 // First, handle some easy cases. We know the result cannot be equal at this
7172 // point so handle the ICI.isEquality() cases
7173 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007174 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007175 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007176 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007177
7178 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7179 // should have been folded away previously and not enter in here.
7180 Value *Result;
7181 if (isSignedCmp) {
7182 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007183 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007184 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007185 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007186 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007187 } else {
7188 // We're performing an unsigned comparison.
7189 if (isSignedExt) {
7190 // We're performing an unsigned comp with a sign extended value.
7191 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007192 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007193 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007194 } else {
7195 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007196 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007197 }
7198 }
7199
7200 // Finally, return the value computed.
7201 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007202 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007203 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007204
7205 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7206 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7207 "ICmp should be folded!");
7208 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007209 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007210 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007211}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007212
Reid Spencer832254e2007-02-02 02:16:23 +00007213Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7214 return commonShiftTransforms(I);
7215}
7216
7217Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7218 return commonShiftTransforms(I);
7219}
7220
7221Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007222 if (Instruction *R = commonShiftTransforms(I))
7223 return R;
7224
7225 Value *Op0 = I.getOperand(0);
7226
7227 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7228 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7229 if (CSI->isAllOnesValue())
7230 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007231
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007232 // See if we can turn a signed shr into an unsigned shr.
7233 if (MaskedValueIsZero(Op0,
7234 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7235 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7236
7237 // Arithmetic shifting an all-sign-bit value is a no-op.
7238 unsigned NumSignBits = ComputeNumSignBits(Op0);
7239 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7240 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007241
Chris Lattner348f6652007-12-06 01:59:46 +00007242 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007243}
7244
7245Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7246 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007247 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007248
7249 // shl X, 0 == X and shr X, 0 == X
7250 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007251 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7252 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007253 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007254
Reid Spencere4d87aa2006-12-23 06:05:41 +00007255 if (isa<UndefValue>(Op0)) {
7256 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007257 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007258 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007259 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007260 }
7261 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007262 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7263 return ReplaceInstUsesWith(I, Op0);
7264 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007265 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007266 }
7267
Dan Gohman9004c8a2009-05-21 02:28:33 +00007268 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007269 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007270 return &I;
7271
Chris Lattner2eefe512004-04-09 19:05:30 +00007272 // Try to fold constant and into select arguments.
7273 if (isa<Constant>(Op0))
7274 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007275 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007276 return R;
7277
Reid Spencerb83eb642006-10-20 07:07:24 +00007278 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007279 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7280 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007281 return 0;
7282}
7283
Reid Spencerb83eb642006-10-20 07:07:24 +00007284Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007285 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007286 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007287
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007288 // See if we can simplify any instructions used by the instruction whose sole
7289 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007290 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007291
Dan Gohmana119de82009-06-14 23:30:43 +00007292 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7293 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007294 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007295 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007296 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007297 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007298 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007299 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007300 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007301 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007302 }
7303
7304 // ((X*C1) << C2) == (X * (C1 << C2))
7305 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7306 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7307 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007308 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007309 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007310
7311 // Try to fold constant and into select arguments.
7312 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7313 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7314 return R;
7315 if (isa<PHINode>(Op0))
7316 if (Instruction *NV = FoldOpIntoPhi(I))
7317 return NV;
7318
Chris Lattner8999dd32007-12-22 09:07:47 +00007319 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7320 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7321 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7322 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7323 // place. Don't try to do this transformation in this case. Also, we
7324 // require that the input operand is a shift-by-constant so that we have
7325 // confidence that the shifts will get folded together. We could do this
7326 // xform in more cases, but it is unlikely to be profitable.
7327 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7328 isa<ConstantInt>(TrOp->getOperand(1))) {
7329 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007330 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007331 // (shift2 (shift1 & 0x00FF), c2)
7332 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007333
7334 // For logical shifts, the truncation has the effect of making the high
7335 // part of the register be zeros. Emulate this by inserting an AND to
7336 // clear the top bits as needed. This 'and' will usually be zapped by
7337 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007338 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7339 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007340 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7341
7342 // The mask we constructed says what the trunc would do if occurring
7343 // between the shifts. We want to know the effect *after* the second
7344 // shift. We know that it is a logical shift by a constant, so adjust the
7345 // mask as appropriate.
7346 if (I.getOpcode() == Instruction::Shl)
7347 MaskV <<= Op1->getZExtValue();
7348 else {
7349 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7350 MaskV = MaskV.lshr(Op1->getZExtValue());
7351 }
7352
Chris Lattner74381062009-08-30 07:44:24 +00007353 // shift1 & 0x00FF
7354 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7355 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007356
7357 // Return the value truncated to the interesting size.
7358 return new TruncInst(And, I.getType());
7359 }
7360 }
7361
Chris Lattner4d5542c2006-01-06 07:12:35 +00007362 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007363 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7364 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7365 Value *V1, *V2;
7366 ConstantInt *CC;
7367 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007368 default: break;
7369 case Instruction::Add:
7370 case Instruction::And:
7371 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007372 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007373 // These operators commute.
7374 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007375 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007376 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007377 m_Specific(Op1)))) {
7378 Value *YS = // (Y << C)
7379 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7380 // (X + (Y << C))
7381 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7382 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007383 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007384 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007385 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007386 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007387
Chris Lattner150f12a2005-09-18 06:30:59 +00007388 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007389 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007390 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007391 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007392 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007393 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007394 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007395 Value *YS = // (Y << C)
7396 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7397 Op0BO->getName());
7398 // X & (CC << C)
7399 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7400 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007401 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007402 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007403 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007404
Reid Spencera07cb7d2007-02-02 14:41:37 +00007405 // FALL THROUGH.
7406 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007407 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007408 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007409 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007410 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007411 Value *YS = // (Y << C)
7412 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7413 // (X + (Y << C))
7414 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7415 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007416 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007417 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007418 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007419 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007420
Chris Lattner13d4ab42006-05-31 21:14:00 +00007421 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007422 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7423 match(Op0BO->getOperand(0),
7424 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007425 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00007426 cast<BinaryOperator>(Op0BO->getOperand(0))
7427 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007428 Value *YS = // (Y << C)
7429 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7430 // X & (CC << C)
7431 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7432 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00007433
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007434 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00007435 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007436
Chris Lattner11021cb2005-09-18 05:12:10 +00007437 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00007438 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007439 }
7440
7441
7442 // If the operand is an bitwise operator with a constant RHS, and the
7443 // shift is the only use, we can pull it out of the shift.
7444 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7445 bool isValid = true; // Valid only for And, Or, Xor
7446 bool highBitSet = false; // Transform if high bit of constant set?
7447
7448 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00007449 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00007450 case Instruction::Add:
7451 isValid = isLeftShift;
7452 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00007453 case Instruction::Or:
7454 case Instruction::Xor:
7455 highBitSet = false;
7456 break;
7457 case Instruction::And:
7458 highBitSet = true;
7459 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007460 }
7461
7462 // If this is a signed shift right, and the high bit is modified
7463 // by the logical operation, do not perform the transformation.
7464 // The highBitSet boolean indicates the value of the high bit of
7465 // the constant which would cause it to be modified for this
7466 // operation.
7467 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00007468 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00007469 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007470
7471 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007472 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007473
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007474 Value *NewShift =
7475 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00007476 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00007477
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007478 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00007479 NewRHS);
7480 }
7481 }
7482 }
7483 }
7484
Chris Lattnerad0124c2006-01-06 07:52:12 +00007485 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00007486 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7487 if (ShiftOp && !ShiftOp->isShift())
7488 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007489
Reid Spencerb83eb642006-10-20 07:07:24 +00007490 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00007491 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007492 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7493 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007494 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7495 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7496 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00007497
Zhou Sheng4351c642007-04-02 08:20:41 +00007498 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00007499
7500 const IntegerType *Ty = cast<IntegerType>(I.getType());
7501
7502 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00007503 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007504 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7505 // saturates.
7506 if (AmtSum >= TypeBits) {
7507 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007508 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007509 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7510 }
7511
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007512 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00007513 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007514 }
7515
7516 if (ShiftOp->getOpcode() == Instruction::LShr &&
7517 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00007518 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00007519 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00007520
Chris Lattnerb87056f2007-02-05 00:57:54 +00007521 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00007522 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007523 }
7524
7525 if (ShiftOp->getOpcode() == Instruction::AShr &&
7526 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00007527 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00007528 if (AmtSum >= TypeBits)
7529 AmtSum = TypeBits-1;
7530
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007531 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007532
Zhou Shenge9e03f62007-03-28 15:02:20 +00007533 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007534 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007535 }
7536
Chris Lattnerb87056f2007-02-05 00:57:54 +00007537 // Okay, if we get here, one shift must be left, and the other shift must be
7538 // right. See if the amounts are equal.
7539 if (ShiftAmt1 == ShiftAmt2) {
7540 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7541 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00007542 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007543 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007544 }
7545 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7546 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00007547 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007548 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007549 }
7550 // We can simplify ((X << C) >>s C) into a trunc + sext.
7551 // NOTE: we could do this for any C, but that would make 'unusual' integer
7552 // types. For now, just stick to ones well-supported by the code
7553 // generators.
7554 const Type *SExtType = 0;
7555 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00007556 case 1 :
7557 case 8 :
7558 case 16 :
7559 case 32 :
7560 case 64 :
7561 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00007562 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00007563 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007564 default: break;
7565 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007566 if (SExtType)
7567 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00007568 // Otherwise, we can't handle it yet.
7569 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00007570 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00007571
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007572 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007573 if (I.getOpcode() == Instruction::Shl) {
7574 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7575 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007576 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +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 Lattnerad0124c2006-01-06 07:52:12 +00007581 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007582
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007583 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-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->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00007587
Reid Spencerd5e30f02007-03-26 17:18:58 +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 Lattner11021cb2005-09-18 05:12:10 +00007591 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00007592
7593 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7594 } else {
7595 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00007596 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00007597
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007598 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007599 if (I.getOpcode() == Instruction::Shl) {
7600 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7601 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007602 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7603 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007604
Reid Spencer55702aa2007-03-25 21:11:44 +00007605 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007606 return BinaryOperator::CreateAnd(Shift,
7607 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007608 }
7609
Chris Lattnerb0b991a2007-02-05 05:57:49 +00007610 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00007611 if (I.getOpcode() == Instruction::LShr) {
7612 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007613 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007614
Reid Spencer68d27cf2007-03-26 23:45:51 +00007615 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00007616 return BinaryOperator::CreateAnd(Shift,
7617 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00007618 }
7619
7620 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007621 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00007622 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007623 return 0;
7624}
7625
Chris Lattnera1be5662002-05-02 17:06:02 +00007626
Chris Lattnercfd65102005-10-29 04:36:15 +00007627/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7628/// expression. If so, decompose it, returning some value X, such that Val is
7629/// X*Scale+Offset.
7630///
7631static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00007632 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007633 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7634 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00007635 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00007636 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00007637 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00007638 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00007639 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7640 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7641 if (I->getOpcode() == Instruction::Shl) {
7642 // This is a value scaled by '1 << the shift amt'.
7643 Scale = 1U << RHS->getZExtValue();
7644 Offset = 0;
7645 return I->getOperand(0);
7646 } else if (I->getOpcode() == Instruction::Mul) {
7647 // This value is scaled by 'RHS'.
7648 Scale = RHS->getZExtValue();
7649 Offset = 0;
7650 return I->getOperand(0);
7651 } else if (I->getOpcode() == Instruction::Add) {
7652 // We have X+C. Check to see if we really have (X*C2)+C1,
7653 // where C1 is divisible by C2.
7654 unsigned SubScale;
7655 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00007656 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7657 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00007658 Offset += RHS->getZExtValue();
7659 Scale = SubScale;
7660 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00007661 }
7662 }
7663 }
7664
7665 // Otherwise, we can't look past this.
7666 Scale = 1;
7667 Offset = 0;
7668 return Val;
7669}
7670
7671
Chris Lattnerb3f83972005-10-24 06:03:58 +00007672/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7673/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007674Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00007675 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007676 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00007677
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007678 BuilderTy AllocaBuilder(*Builder);
7679 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7680
Chris Lattnerb53c2382005-10-24 06:22:12 +00007681 // Remove any uses of AI that are dead.
7682 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00007683
Chris Lattnerb53c2382005-10-24 06:22:12 +00007684 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7685 Instruction *User = cast<Instruction>(*UI++);
7686 if (isInstructionTriviallyDead(User)) {
7687 while (UI != E && *UI == User)
7688 ++UI; // If this instruction uses AI more than once, don't break UI.
7689
Chris Lattnerb53c2382005-10-24 06:22:12 +00007690 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00007691 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00007692 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00007693 }
7694 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007695
7696 // This requires TargetData to get the alloca alignment and size information.
7697 if (!TD) return 0;
7698
Chris Lattnerb3f83972005-10-24 06:03:58 +00007699 // Get the type really allocated and the type casted to.
7700 const Type *AllocElTy = AI.getAllocatedType();
7701 const Type *CastElTy = PTy->getElementType();
7702 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007703
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007704 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7705 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00007706 if (CastElTyAlign < AllocElTyAlign) return 0;
7707
Chris Lattner39387a52005-10-24 06:35:18 +00007708 // If the allocation has multiple uses, only promote it if we are strictly
7709 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00007710 // same, we open the door to infinite loops of various kinds. (A reference
7711 // from a dbg.declare doesn't count as a use for this purpose.)
7712 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7713 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00007714
Duncan Sands777d2302009-05-09 07:06:46 +00007715 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7716 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007717 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00007718
Chris Lattner455fcc82005-10-29 03:19:53 +00007719 // See if we can satisfy the modulus by pulling a scale out of the array
7720 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00007721 unsigned ArraySizeScale;
7722 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00007723 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00007724 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7725 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00007726
Chris Lattner455fcc82005-10-29 03:19:53 +00007727 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7728 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00007729 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7730 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00007731
Chris Lattner455fcc82005-10-29 03:19:53 +00007732 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7733 Value *Amt = 0;
7734 if (Scale == 1) {
7735 Amt = NumElements;
7736 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00007737 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007738 // Insert before the alloca, not before the cast.
7739 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00007740 }
7741
Jeff Cohen86796be2007-04-04 16:58:57 +00007742 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00007743 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007744 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00007745 }
7746
Chris Lattnerb3f83972005-10-24 06:03:58 +00007747 AllocationInst *New;
7748 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007749 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
Chris Lattnerb3f83972005-10-24 06:03:58 +00007750 else
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007751 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7752 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00007753 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00007754
Dale Johannesena0a66372009-03-05 00:39:02 +00007755 // If the allocation has one real use plus a dbg.declare, just remove the
7756 // declare.
7757 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7758 EraseInstFromFunction(*DI);
7759 }
7760 // If the allocation has multiple real uses, insert a cast and change all
7761 // things that used it to use the new cast. This will also hack on CI, but it
7762 // will die soon.
7763 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007764 // New is the allocation instruction, pointer typed. AI is the original
7765 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007766 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00007767 AI.replaceAllUsesWith(NewCast);
7768 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00007769 return ReplaceInstUsesWith(CI, New);
7770}
7771
Chris Lattner70074e02006-05-13 02:06:03 +00007772/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00007773/// and return it as type Ty without inserting any new casts and without
7774/// changing the computed value. This is used by code that tries to decide
7775/// whether promoting or shrinking integer operations to wider or smaller types
7776/// will allow us to eliminate a truncate or extend.
7777///
7778/// This is a truncation operation if Ty is smaller than V->getType(), or an
7779/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00007780///
7781/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7782/// should return true if trunc(V) can be computed by computing V in the smaller
7783/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7784/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7785/// efficiently truncated.
7786///
7787/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7788/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7789/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00007790bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007791 unsigned CastOpc,
7792 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00007793 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00007794 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00007795 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00007796
7797 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007798 if (!I) return false;
7799
Dan Gohman6de29f82009-06-15 22:12:54 +00007800 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00007801
Chris Lattner951626b2007-08-02 06:11:14 +00007802 // If this is an extension or truncate, we can often eliminate it.
7803 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7804 // If this is a cast from the destination type, we can trivially eliminate
7805 // it, and this will remove a cast overall.
7806 if (I->getOperand(0)->getType() == Ty) {
7807 // If the first operand is itself a cast, and is eliminable, do not count
7808 // this as an eliminable cast. We would prefer to eliminate those two
7809 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00007810 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00007811 ++NumCastsRemoved;
7812 return true;
7813 }
7814 }
7815
7816 // We can't extend or shrink something that has multiple uses: doing so would
7817 // require duplicating the instruction in general, which isn't profitable.
7818 if (!I->hasOneUse()) return false;
7819
Evan Chengf35fd542009-01-15 17:01:23 +00007820 unsigned Opc = I->getOpcode();
7821 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007822 case Instruction::Add:
7823 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007824 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007825 case Instruction::And:
7826 case Instruction::Or:
7827 case Instruction::Xor:
7828 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00007829 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007830 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00007831 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007832 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007833
Eli Friedman070a9812009-07-13 22:46:01 +00007834 case Instruction::UDiv:
7835 case Instruction::URem: {
7836 // UDiv and URem can be truncated if all the truncated bits are zero.
7837 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7838 uint32_t BitWidth = Ty->getScalarSizeInBits();
7839 if (BitWidth < OrigBitWidth) {
7840 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7841 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7842 MaskedValueIsZero(I->getOperand(1), Mask)) {
7843 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7844 NumCastsRemoved) &&
7845 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7846 NumCastsRemoved);
7847 }
7848 }
7849 break;
7850 }
Chris Lattner46b96052006-11-29 07:18:39 +00007851 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007852 // If we are truncating the result of this SHL, and if it's a shift of a
7853 // constant amount, we can always perform a SHL in a smaller type.
7854 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007855 uint32_t BitWidth = Ty->getScalarSizeInBits();
7856 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00007857 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00007858 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007859 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007860 }
7861 break;
7862 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007863 // If this is a truncate of a logical shr, we can truncate it to a smaller
7864 // lshr iff we know that the bits we would otherwise be shifting in are
7865 // already zeros.
7866 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00007867 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7868 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00007869 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00007870 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00007871 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7872 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00007873 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007874 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007875 }
7876 }
Chris Lattner46b96052006-11-29 07:18:39 +00007877 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007878 case Instruction::ZExt:
7879 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00007880 case Instruction::Trunc:
7881 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00007882 // can safely replace it. Note that replacing it does not reduce the number
7883 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00007884 if (Opc == CastOpc)
7885 return true;
7886
7887 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00007888 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00007889 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00007890 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007891 case Instruction::Select: {
7892 SelectInst *SI = cast<SelectInst>(I);
7893 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007894 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007895 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007896 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007897 }
Chris Lattner8114b712008-06-18 04:00:49 +00007898 case Instruction::PHI: {
7899 // We can change a phi if we can change all operands.
7900 PHINode *PN = cast<PHINode>(I);
7901 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7902 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00007903 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00007904 return false;
7905 return true;
7906 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007907 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007908 // TODO: Can handle more cases here.
7909 break;
7910 }
7911
7912 return false;
7913}
7914
7915/// EvaluateInDifferentType - Given an expression that
7916/// CanEvaluateInDifferentType returns true for, actually insert the code to
7917/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00007918Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00007919 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00007920 if (Constant *C = dyn_cast<Constant>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007921 return ConstantExpr::getIntegerCast(C, Ty,
Owen Andersond672ecb2009-07-03 00:17:18 +00007922 isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00007923
7924 // Otherwise, it must be an instruction.
7925 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00007926 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00007927 unsigned Opc = I->getOpcode();
7928 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00007929 case Instruction::Add:
7930 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00007931 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00007932 case Instruction::And:
7933 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00007934 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00007935 case Instruction::AShr:
7936 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00007937 case Instruction::Shl:
7938 case Instruction::UDiv:
7939 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00007940 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00007941 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00007942 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00007943 break;
7944 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007945 case Instruction::Trunc:
7946 case Instruction::ZExt:
7947 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00007948 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00007949 // just return the source. There's no need to insert it because it is not
7950 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00007951 if (I->getOperand(0)->getType() == Ty)
7952 return I->getOperand(0);
7953
Chris Lattner8114b712008-06-18 04:00:49 +00007954 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007955 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner8114b712008-06-18 04:00:49 +00007956 Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00007957 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00007958 case Instruction::Select: {
7959 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7960 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7961 Res = SelectInst::Create(I->getOperand(0), True, False);
7962 break;
7963 }
Chris Lattner8114b712008-06-18 04:00:49 +00007964 case Instruction::PHI: {
7965 PHINode *OPN = cast<PHINode>(I);
7966 PHINode *NPN = PHINode::Create(Ty);
7967 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7968 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7969 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7970 }
7971 Res = NPN;
7972 break;
7973 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007974 default:
Chris Lattner70074e02006-05-13 02:06:03 +00007975 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00007976 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00007977 break;
7978 }
7979
Chris Lattner8114b712008-06-18 04:00:49 +00007980 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00007981 return InsertNewInstBefore(Res, *I);
7982}
7983
Reid Spencer3da59db2006-11-27 01:05:10 +00007984/// @brief Implement the transforms common to all CastInst visitors.
7985Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00007986 Value *Src = CI.getOperand(0);
7987
Dan Gohman23d9d272007-05-11 21:10:54 +00007988 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00007989 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00007990 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007991 if (Instruction::CastOps opc =
7992 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7993 // The first cast (CSrc) is eliminable so we need to fix up or replace
7994 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007995 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00007996 }
7997 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00007998
Reid Spencer3da59db2006-11-27 01:05:10 +00007999 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008000 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8001 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8002 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008003
8004 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00008005 if (isa<PHINode>(Src))
8006 if (Instruction *NV = FoldOpIntoPhi(CI))
8007 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00008008
Reid Spencer3da59db2006-11-27 01:05:10 +00008009 return 0;
8010}
8011
Chris Lattner46cd5a12009-01-09 05:44:56 +00008012/// FindElementAtOffset - Given a type and a constant offset, determine whether
8013/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008014/// the specified offset. If so, fill them into NewIndices and return the
8015/// resultant element type, otherwise return null.
8016static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8017 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008018 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008019 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008020 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008021 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008022
8023 // Start with the index over the outer type. Note that the type size
8024 // might be zero (even if the offset isn't zero) if the indexed type
8025 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008026 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008027 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008028 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008029 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008030 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008031
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008032 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008033 if (Offset < 0) {
8034 --FirstIdx;
8035 Offset += TySize;
8036 assert(Offset >= 0);
8037 }
8038 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8039 }
8040
Owen Andersoneed707b2009-07-24 23:12:02 +00008041 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008042
8043 // Index into the types. If we fail, set OrigBase to null.
8044 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008045 // Indexing into tail padding between struct/array elements.
8046 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008047 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008048
Chris Lattner46cd5a12009-01-09 05:44:56 +00008049 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8050 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008051 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8052 "Offset must stay within the indexed type");
8053
Chris Lattner46cd5a12009-01-09 05:44:56 +00008054 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008055 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008056
8057 Offset -= SL->getElementOffset(Elt);
8058 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008059 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008060 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008061 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008062 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008063 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008064 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008065 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008066 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008067 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008068 }
8069 }
8070
Chris Lattner3914f722009-01-24 01:00:13 +00008071 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008072}
8073
Chris Lattnerd3e28342007-04-27 17:44:50 +00008074/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8075Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8076 Value *Src = CI.getOperand(0);
8077
Chris Lattnerd3e28342007-04-27 17:44:50 +00008078 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008079 // If casting the result of a getelementptr instruction with no offset, turn
8080 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008081 if (GEP->hasAllZeroIndices()) {
8082 // Changing the cast operand is usually not a good idea but it is safe
8083 // here because the pointer operand is being replaced with another
8084 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008085 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008086 CI.setOperand(0, GEP->getOperand(0));
8087 return &CI;
8088 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008089
8090 // If the GEP has a single use, and the base pointer is a bitcast, and the
8091 // GEP computes a constant offset, see if we can convert these three
8092 // instructions into fewer. This typically happens with unions and other
8093 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008094 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008095 if (GEP->hasAllConstantIndices()) {
8096 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +00008097 ConstantInt *OffsetV =
8098 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008099 int64_t Offset = OffsetV->getSExtValue();
8100
8101 // Get the base pointer input of the bitcast, and the type it points to.
8102 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8103 const Type *GEPIdxTy =
8104 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008105 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008106 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008107 // If we were able to index down into an element, create the GEP
8108 // and bitcast the result. This eliminates one bitcast, potentially
8109 // two.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008110 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8111 NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008112 NGEP->takeName(GEP);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008113 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008114 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattner9bc14642007-04-28 00:57:34 +00008115
Chris Lattner46cd5a12009-01-09 05:44:56 +00008116 if (isa<BitCastInst>(CI))
8117 return new BitCastInst(NGEP, CI.getType());
8118 assert(isa<PtrToIntInst>(CI));
8119 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008120 }
8121 }
8122 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008123 }
8124
8125 return commonCastTransforms(CI);
8126}
8127
Chris Lattnerddfa57b2009-04-08 05:41:03 +00008128/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8129/// type like i42. We don't want to introduce operations on random non-legal
8130/// integer types where they don't already exist in the code. In the future,
8131/// we should consider making this based off target-data, so that 32-bit targets
8132/// won't get i64 operations etc.
8133static bool isSafeIntegerType(const Type *Ty) {
8134 switch (Ty->getPrimitiveSizeInBits()) {
8135 case 8:
8136 case 16:
8137 case 32:
8138 case 64:
8139 return true;
8140 default:
8141 return false;
8142 }
8143}
Chris Lattnerd3e28342007-04-27 17:44:50 +00008144
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008145/// commonIntCastTransforms - This function implements the common transforms
8146/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008147Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8148 if (Instruction *Result = commonCastTransforms(CI))
8149 return Result;
8150
8151 Value *Src = CI.getOperand(0);
8152 const Type *SrcTy = Src->getType();
8153 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008154 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8155 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008156
Reid Spencer3da59db2006-11-27 01:05:10 +00008157 // See if we can simplify any instructions used by the LHS whose sole
8158 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008159 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008160 return &CI;
8161
8162 // If the source isn't an instruction or has more than one use then we
8163 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008164 Instruction *SrcI = dyn_cast<Instruction>(Src);
8165 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008166 return 0;
8167
Chris Lattnerc739cd62007-03-03 05:27:34 +00008168 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008169 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008170 // Only do this if the dest type is a simple type, don't convert the
8171 // expression tree to something weird like i93 unless the source is also
8172 // strange.
8173 if ((isSafeIntegerType(DestTy->getScalarType()) ||
Dan Gohman6de29f82009-06-15 22:12:54 +00008174 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8175 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008176 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008177 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008178 // eliminates the cast, so it is always a win. If this is a zero-extension,
8179 // we need to do an AND to maintain the clear top-part of the computation,
8180 // so we require that the input have eliminated at least one cast. If this
8181 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008182 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008183 bool DoXForm = false;
8184 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008185 switch (CI.getOpcode()) {
8186 default:
8187 // All the others use floating point so we shouldn't actually
8188 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008189 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008190 case Instruction::Trunc:
8191 DoXForm = true;
8192 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008193 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008194 DoXForm = NumCastsRemoved >= 1;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008195 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008196 // If it's unnecessary to issue an AND to clear the high bits, it's
8197 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008198 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008199 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8200 if (MaskedValueIsZero(TryRes, Mask))
8201 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008202
8203 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008204 if (TryI->use_empty())
8205 EraseInstFromFunction(*TryI);
8206 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008207 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008208 }
Evan Chengf35fd542009-01-15 17:01:23 +00008209 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008210 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008211 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008212 // If we do not have to emit the truncate + sext pair, then it's always
8213 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008214 //
8215 // It's not safe to eliminate the trunc + sext pair if one of the
8216 // eliminated cast is a truncate. e.g.
8217 // t2 = trunc i32 t1 to i16
8218 // t3 = sext i16 t2 to i32
8219 // !=
8220 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008221 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008222 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8223 if (NumSignBits > (DestBitSize - SrcBitSize))
8224 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008225
8226 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008227 if (TryI->use_empty())
8228 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008229 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008230 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008231 }
Evan Chengf35fd542009-01-15 17:01:23 +00008232 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008233
8234 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008235 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8236 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008237 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8238 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008239 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008240 // Just replace this cast with the result.
8241 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008242
Reid Spencer3da59db2006-11-27 01:05:10 +00008243 assert(Res->getType() == DestTy);
8244 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008245 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008246 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008247 // Just replace this cast with the result.
8248 return ReplaceInstUsesWith(CI, Res);
8249 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008250 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008251
8252 // If the high bits are already zero, just replace this cast with the
8253 // result.
8254 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8255 if (MaskedValueIsZero(Res, Mask))
8256 return ReplaceInstUsesWith(CI, Res);
8257
8258 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008259 Constant *C = ConstantInt::get(*Context,
8260 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008261 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008262 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008263 case Instruction::SExt: {
8264 // If the high bits are already filled with sign bit, just replace this
8265 // cast with the result.
8266 unsigned NumSignBits = ComputeNumSignBits(Res);
8267 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008268 return ReplaceInstUsesWith(CI, Res);
8269
Reid Spencer3da59db2006-11-27 01:05:10 +00008270 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008271 return CastInst::Create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00008272 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8273 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008274 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008275 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008276 }
8277 }
8278
8279 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8280 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8281
8282 switch (SrcI->getOpcode()) {
8283 case Instruction::Add:
8284 case Instruction::Mul:
8285 case Instruction::And:
8286 case Instruction::Or:
8287 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008288 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008289 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8290 // Don't insert two casts unless at least one can be eliminated.
8291 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008292 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman65445c52009-07-13 21:45:57 +00008293 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8294 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008295 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008296 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008297 }
8298 }
8299
8300 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8301 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8302 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008303 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008304 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008305 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Andersond672ecb2009-07-03 00:17:18 +00008306 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008307 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008308 }
8309 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008310
Eli Friedman65445c52009-07-13 21:45:57 +00008311 case Instruction::Shl: {
8312 // Canonicalize trunc inside shl, if we can.
8313 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8314 if (CI && DestBitSize < SrcBitSize &&
8315 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8316 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8317 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008318 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008319 }
8320 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008321 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008322 }
8323 return 0;
8324}
8325
Chris Lattner8a9f5712007-04-11 06:57:46 +00008326Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008327 if (Instruction *Result = commonIntCastTransforms(CI))
8328 return Result;
8329
8330 Value *Src = CI.getOperand(0);
8331 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008332 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8333 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008334
8335 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008336 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008337 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008338 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008339 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008340 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008341 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008342
Chris Lattner4f9797d2009-03-24 18:15:30 +00008343 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8344 ConstantInt *ShAmtV = 0;
8345 Value *ShiftOp = 0;
8346 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008347 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008348 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8349
8350 // Get a mask for the bits shifting in.
8351 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8352 if (MaskedValueIsZero(ShiftOp, Mask)) {
8353 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008354 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008355
8356 // Okay, we can shrink this. Truncate the input, then return a new
8357 // shift.
8358 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008359 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008360 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008361 }
8362 }
8363
8364 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008365}
8366
Evan Chengb98a10e2008-03-24 00:21:34 +00008367/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8368/// in order to eliminate the icmp.
8369Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8370 bool DoXform) {
8371 // If we are just checking for a icmp eq of a single bit and zext'ing it
8372 // to an integer, then shift the bit to the appropriate place and then
8373 // cast to integer to avoid the comparison.
8374 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8375 const APInt &Op1CV = Op1C->getValue();
8376
8377 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8378 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8379 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8380 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8381 if (!DoXform) return ICI;
8382
8383 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008384 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008385 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008386 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008387 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008388 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008389
8390 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008391 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008392 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008393 }
8394
8395 return ReplaceInstUsesWith(CI, In);
8396 }
8397
8398
8399
8400 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8401 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8402 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8403 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8404 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8405 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8406 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8407 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8408 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8409 // This only works for EQ and NE
8410 ICI->isEquality()) {
8411 // If Op1C some other power of two, convert:
8412 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8413 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8414 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8415 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8416
8417 APInt KnownZeroMask(~KnownZero);
8418 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8419 if (!DoXform) return ICI;
8420
8421 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8422 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8423 // (X&4) == 2 --> false
8424 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008425 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008426 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008427 return ReplaceInstUsesWith(CI, Res);
8428 }
8429
8430 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8431 Value *In = ICI->getOperand(0);
8432 if (ShiftAmt) {
8433 // Perform a logical shr by shiftamt.
8434 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008435 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8436 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008437 }
8438
8439 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008440 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008441 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008442 }
8443
8444 if (CI.getType() == In->getType())
8445 return ReplaceInstUsesWith(CI, In);
8446 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008447 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00008448 }
8449 }
8450 }
8451
8452 return 0;
8453}
8454
Chris Lattner8a9f5712007-04-11 06:57:46 +00008455Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008456 // If one of the common conversion will work ..
8457 if (Instruction *Result = commonIntCastTransforms(CI))
8458 return Result;
8459
8460 Value *Src = CI.getOperand(0);
8461
Chris Lattnera84f47c2009-02-17 20:47:23 +00008462 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8463 // types and if the sizes are just right we can convert this into a logical
8464 // 'and' which will be much cheaper than the pair of casts.
8465 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8466 // Get the sizes of the types involved. We know that the intermediate type
8467 // will be smaller than A or C, but don't know the relation between A and C.
8468 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008469 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8470 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8471 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00008472 // If we're actually extending zero bits, then if
8473 // SrcSize < DstSize: zext(a & mask)
8474 // SrcSize == DstSize: a & mask
8475 // SrcSize > DstSize: trunc(a) & mask
8476 if (SrcSize < DstSize) {
8477 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008478 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008479 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008480 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008481 }
8482
8483 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00008484 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00008485 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008486 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008487 }
8488 if (SrcSize > DstSize) {
8489 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00008490 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00008491 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00008492 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008493 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00008494 }
8495 }
8496
Evan Chengb98a10e2008-03-24 00:21:34 +00008497 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8498 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00008499
Evan Chengb98a10e2008-03-24 00:21:34 +00008500 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8501 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8502 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8503 // of the (zext icmp) will be transformed.
8504 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8505 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8506 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8507 (transformZExtICmp(LHS, CI, false) ||
8508 transformZExtICmp(RHS, CI, false))) {
8509 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8510 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008511 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00008512 }
Evan Chengb98a10e2008-03-24 00:21:34 +00008513 }
8514
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008515 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00008516 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8517 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8518 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8519 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008520 if (TI0->getType() == CI.getType())
8521 return
8522 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00008523 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00008524 }
8525
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008526 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8527 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8528 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8529 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8530 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8531 And->getOperand(1) == C)
8532 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8533 Value *TI0 = TI->getOperand(0);
8534 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008535 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008536 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00008537 return BinaryOperator::CreateXor(NewAnd, ZC);
8538 }
8539 }
8540
Reid Spencer3da59db2006-11-27 01:05:10 +00008541 return 0;
8542}
8543
Chris Lattner8a9f5712007-04-11 06:57:46 +00008544Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00008545 if (Instruction *I = commonIntCastTransforms(CI))
8546 return I;
8547
Chris Lattner8a9f5712007-04-11 06:57:46 +00008548 Value *Src = CI.getOperand(0);
8549
Dan Gohman1975d032008-10-30 20:40:10 +00008550 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00008551 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00008552 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00008553 Constant::getAllOnesValue(CI.getType()),
8554 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00008555
8556 // See if the value being truncated is already sign extended. If so, just
8557 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00008558 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00008559 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00008560 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8561 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8562 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00008563 unsigned NumSignBits = ComputeNumSignBits(Op);
8564
8565 if (OpBits == DestBits) {
8566 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8567 // bits, it is already ready.
8568 if (NumSignBits > DestBits-MidBits)
8569 return ReplaceInstUsesWith(CI, Op);
8570 } else if (OpBits < DestBits) {
8571 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8572 // bits, just sext from i32.
8573 if (NumSignBits > OpBits-MidBits)
8574 return new SExtInst(Op, CI.getType(), "tmp");
8575 } else {
8576 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8577 // bits, just truncate to i32.
8578 if (NumSignBits > OpBits-MidBits)
8579 return new TruncInst(Op, CI.getType(), "tmp");
8580 }
8581 }
Chris Lattner46bbad22008-08-06 07:35:52 +00008582
8583 // If the input is a shl/ashr pair of a same constant, then this is a sign
8584 // extension from a smaller value. If we could trust arbitrary bitwidth
8585 // integers, we could turn this into a truncate to the smaller bit and then
8586 // use a sext for the whole extension. Since we don't, look deeper and check
8587 // for a truncate. If the source and dest are the same type, eliminate the
8588 // trunc and extend and just do shifts. For example, turn:
8589 // %a = trunc i32 %i to i8
8590 // %b = shl i8 %a, 6
8591 // %c = ashr i8 %b, 6
8592 // %d = sext i8 %c to i32
8593 // into:
8594 // %a = shl i32 %i, 30
8595 // %d = ashr i32 %a, 30
8596 Value *A = 0;
8597 ConstantInt *BA = 0, *CA = 0;
8598 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008599 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00008600 BA == CA && isa<TruncInst>(A)) {
8601 Value *I = cast<TruncInst>(A)->getOperand(0);
8602 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008603 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8604 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00008605 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00008606 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008607 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00008608 return BinaryOperator::CreateAShr(I, ShAmtV);
8609 }
8610 }
8611
Chris Lattnerba417832007-04-11 06:12:58 +00008612 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008613}
8614
Chris Lattnerb7530652008-01-27 05:29:54 +00008615/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8616/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00008617static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008618 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00008619 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00008620 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00008621 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8622 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00008623 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00008624 return 0;
8625}
8626
8627/// LookThroughFPExtensions - If this is an fp extension instruction, look
8628/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00008629static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008630 if (Instruction *I = dyn_cast<Instruction>(V))
8631 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00008632 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008633
8634 // If this value is a constant, return the constant in the smallest FP type
8635 // that can accurately represent it. This allows us to turn
8636 // (float)((double)X+2.0) into x+2.0f.
8637 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008638 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008639 return V; // No constant folding of this.
8640 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00008641 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008642 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00008643 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008644 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00008645 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00008646 return V;
8647 // Don't try to shrink to various long double types.
8648 }
8649
8650 return V;
8651}
8652
8653Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8654 if (Instruction *I = commonCastTransforms(CI))
8655 return I;
8656
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008657 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00008658 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008659 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00008660 // many builtins (sqrt, etc).
8661 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8662 if (OpI && OpI->hasOneUse()) {
8663 switch (OpI->getOpcode()) {
8664 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00008665 case Instruction::FAdd:
8666 case Instruction::FSub:
8667 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00008668 case Instruction::FDiv:
8669 case Instruction::FRem:
8670 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00008671 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8672 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00008673 if (LHSTrunc->getType() != SrcTy &&
8674 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008675 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00008676 // If the source types were both smaller than the destination type of
8677 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00008678 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8679 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerb7530652008-01-27 05:29:54 +00008680 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8681 CI.getType(), CI);
8682 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8683 CI.getType(), CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008684 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00008685 }
8686 }
8687 break;
8688 }
8689 }
8690 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008691}
8692
8693Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8694 return commonCastTransforms(CI);
8695}
8696
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008697Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008698 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8699 if (OpI == 0)
8700 return commonCastTransforms(FI);
8701
8702 // fptoui(uitofp(X)) --> X
8703 // fptoui(sitofp(X)) --> X
8704 // This is safe if the intermediate type has enough bits in its mantissa to
8705 // accurately represent all values of X. For example, do not do this with
8706 // i64->float->i64. This is also safe for sitofp case, because any negative
8707 // 'X' value would cause an undefined result for the fptoui.
8708 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8709 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008710 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00008711 OpI->getType()->getFPMantissaWidth())
8712 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008713
8714 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008715}
8716
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008717Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00008718 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8719 if (OpI == 0)
8720 return commonCastTransforms(FI);
8721
8722 // fptosi(sitofp(X)) --> X
8723 // fptosi(uitofp(X)) --> X
8724 // This is safe if the intermediate type has enough bits in its mantissa to
8725 // accurately represent all values of X. For example, do not do this with
8726 // i64->float->i64. This is also safe for sitofp case, because any negative
8727 // 'X' value would cause an undefined result for the fptoui.
8728 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8729 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00008730 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00008731 OpI->getType()->getFPMantissaWidth())
8732 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00008733
8734 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008735}
8736
8737Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8738 return commonCastTransforms(CI);
8739}
8740
8741Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8742 return commonCastTransforms(CI);
8743}
8744
Chris Lattnera0e69692009-03-24 18:35:40 +00008745Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8746 // If the destination integer type is smaller than the intptr_t type for
8747 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8748 // trunc to be exposed to other transforms. Don't do this for extending
8749 // ptrtoint's, because we don't know if the target sign or zero extends its
8750 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008751 if (TD &&
8752 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008753 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8754 TD->getIntPtrType(CI.getContext()),
8755 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008756 return new TruncInst(P, CI.getType());
8757 }
8758
Chris Lattnerd3e28342007-04-27 17:44:50 +00008759 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008760}
8761
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008762Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00008763 // If the source integer type is larger than the intptr_t type for
8764 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8765 // allows the trunc to be exposed to other transforms. Don't do this for
8766 // extending inttoptr's, because we don't know if the target sign or zero
8767 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008768 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00008769 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008770 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8771 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00008772 return new IntToPtrInst(P, CI.getType());
8773 }
8774
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008775 if (Instruction *I = commonCastTransforms(CI))
8776 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008777
Chris Lattnerf9d9e452008-01-08 07:23:51 +00008778 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008779}
8780
Chris Lattnerd3e28342007-04-27 17:44:50 +00008781Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008782 // If the operands are integer typed then apply the integer transforms,
8783 // otherwise just apply the common ones.
8784 Value *Src = CI.getOperand(0);
8785 const Type *SrcTy = Src->getType();
8786 const Type *DestTy = CI.getType();
8787
Eli Friedman7e25d452009-07-13 20:53:00 +00008788 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008789 if (Instruction *I = commonPointerCastTransforms(CI))
8790 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00008791 } else {
8792 if (Instruction *Result = commonCastTransforms(CI))
8793 return Result;
8794 }
8795
8796
8797 // Get rid of casts from one type to the same type. These are useless and can
8798 // be replaced by the operand.
8799 if (DestTy == Src->getType())
8800 return ReplaceInstUsesWith(CI, Src);
8801
Reid Spencer3da59db2006-11-27 01:05:10 +00008802 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008803 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8804 const Type *DstElTy = DstPTy->getElementType();
8805 const Type *SrcElTy = SrcPTy->getElementType();
8806
Nate Begeman83ad90a2008-03-31 00:22:16 +00008807 // If the address spaces don't match, don't eliminate the bitcast, which is
8808 // required for changing types.
8809 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8810 return 0;
8811
Chris Lattnerd3e28342007-04-27 17:44:50 +00008812 // If we are casting a malloc or alloca to a pointer to a type of the same
8813 // size, rewrite the allocation instruction to allocate the "right" type.
8814 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8815 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8816 return V;
8817
Chris Lattnerd717c182007-05-05 22:32:24 +00008818 // If the source and destination are pointers, and this cast is equivalent
8819 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008820 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00008821 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00008822 unsigned NumZeros = 0;
8823 while (SrcElTy != DstElTy &&
8824 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8825 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8826 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8827 ++NumZeros;
8828 }
Chris Lattner4e998b22004-09-29 05:07:12 +00008829
Chris Lattnerd3e28342007-04-27 17:44:50 +00008830 // If we found a path from the src to dest, create the getelementptr now.
8831 if (SrcElTy == DstElTy) {
8832 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00008833 Instruction *GEP = GetElementPtrInst::Create(Src,
8834 Idxs.begin(), Idxs.end(), "",
8835 ((Instruction*) NULL));
8836 cast<GEPOperator>(GEP)->setIsInBounds(true);
8837 return GEP;
Chris Lattner9fb92132006-04-12 18:09:35 +00008838 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008839 }
Chris Lattner24c8e382003-07-24 17:35:25 +00008840
Eli Friedman2451a642009-07-18 23:06:53 +00008841 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8842 if (DestVTy->getNumElements() == 1) {
8843 if (!isa<VectorType>(SrcTy)) {
8844 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
8845 DestVTy->getElementType(), CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00008846 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Owen Anderson1d0be152009-08-13 21:58:54 +00008847 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008848 }
8849 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8850 }
8851 }
8852
8853 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8854 if (SrcVTy->getNumElements() == 1) {
8855 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008856 Value *Elem =
8857 Builder->CreateExtractElement(Src,
8858 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00008859 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8860 }
8861 }
8862 }
8863
Reid Spencer3da59db2006-11-27 01:05:10 +00008864 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8865 if (SVI->hasOneUse()) {
8866 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8867 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008868 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00008869 cast<VectorType>(DestTy)->getNumElements() ==
8870 SVI->getType()->getNumElements() &&
8871 SVI->getType()->getNumElements() ==
8872 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008873 CastInst *Tmp;
8874 // If either of the operands is a cast from CI.getType(), then
8875 // evaluating the shuffle in the casted destination's type will allow
8876 // us to eliminate at least one cast.
8877 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8878 Tmp->getOperand(0)->getType() == DestTy) ||
8879 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8880 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedmand1fd1da2008-11-30 21:09:11 +00008881 Value *LHS = InsertCastBefore(Instruction::BitCast,
8882 SVI->getOperand(0), DestTy, CI);
8883 Value *RHS = InsertCastBefore(Instruction::BitCast,
8884 SVI->getOperand(1), DestTy, CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00008885 // Return a new shuffle vector. Use the same element ID's, as we
8886 // know the vector types match #elts.
8887 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00008888 }
8889 }
8890 }
8891 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00008892 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00008893}
8894
Chris Lattnere576b912004-04-09 23:46:01 +00008895/// GetSelectFoldableOperands - We want to turn code that looks like this:
8896/// %C = or %A, %B
8897/// %D = select %cond, %C, %A
8898/// into:
8899/// %C = select %cond, %B, 0
8900/// %D = or %A, %C
8901///
8902/// Assuming that the specified instruction is an operand to the select, return
8903/// a bitmask indicating which operands of this instruction are foldable if they
8904/// equal the other incoming value of the select.
8905///
8906static unsigned GetSelectFoldableOperands(Instruction *I) {
8907 switch (I->getOpcode()) {
8908 case Instruction::Add:
8909 case Instruction::Mul:
8910 case Instruction::And:
8911 case Instruction::Or:
8912 case Instruction::Xor:
8913 return 3; // Can fold through either operand.
8914 case Instruction::Sub: // Can only fold on the amount subtracted.
8915 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00008916 case Instruction::LShr:
8917 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00008918 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00008919 default:
8920 return 0; // Cannot fold
8921 }
8922}
8923
8924/// GetSelectFoldableConstant - For the same transformation as the previous
8925/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00008926static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008927 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00008928 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008929 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00008930 case Instruction::Add:
8931 case Instruction::Sub:
8932 case Instruction::Or:
8933 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00008934 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00008935 case Instruction::LShr:
8936 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00008937 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008938 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00008939 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00008940 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00008941 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00008942 }
8943}
8944
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008945/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8946/// have the same opcode and only one use each. Try to simplify this.
8947Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8948 Instruction *FI) {
8949 if (TI->getNumOperands() == 1) {
8950 // If this is a non-volatile load or a cast from the same type,
8951 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00008952 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008953 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8954 return 0;
8955 } else {
8956 return 0; // unknown unary op.
8957 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008958
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008959 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00008960 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00008961 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008962 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008963 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00008964 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008965 }
8966
Reid Spencer832254e2007-02-02 02:16:23 +00008967 // Only handle binary operators here.
8968 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00008969 return 0;
8970
8971 // Figure out if the operations have any operands in common.
8972 Value *MatchOp, *OtherOpT, *OtherOpF;
8973 bool MatchIsOpZero;
8974 if (TI->getOperand(0) == FI->getOperand(0)) {
8975 MatchOp = TI->getOperand(0);
8976 OtherOpT = TI->getOperand(1);
8977 OtherOpF = FI->getOperand(1);
8978 MatchIsOpZero = true;
8979 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8980 MatchOp = TI->getOperand(1);
8981 OtherOpT = TI->getOperand(0);
8982 OtherOpF = FI->getOperand(0);
8983 MatchIsOpZero = false;
8984 } else if (!TI->isCommutative()) {
8985 return 0;
8986 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8987 MatchOp = TI->getOperand(0);
8988 OtherOpT = TI->getOperand(1);
8989 OtherOpF = FI->getOperand(0);
8990 MatchIsOpZero = true;
8991 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8992 MatchOp = TI->getOperand(1);
8993 OtherOpT = TI->getOperand(0);
8994 OtherOpF = FI->getOperand(1);
8995 MatchIsOpZero = true;
8996 } else {
8997 return 0;
8998 }
8999
9000 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009001 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9002 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009003 InsertNewInstBefore(NewSI, SI);
9004
9005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9006 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009007 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009008 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009009 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009010 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009011 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009012 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009013}
9014
Evan Chengde621922009-03-31 20:42:45 +00009015static bool isSelect01(Constant *C1, Constant *C2) {
9016 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9017 if (!C1I)
9018 return false;
9019 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9020 if (!C2I)
9021 return false;
9022 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9023}
9024
9025/// FoldSelectIntoOp - Try fold the select into one of the operands to
9026/// facilitate further optimization.
9027Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9028 Value *FalseVal) {
9029 // See the comment above GetSelectFoldableOperands for a description of the
9030 // transformation we are doing here.
9031 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9032 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9033 !isa<Constant>(FalseVal)) {
9034 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9035 unsigned OpToFold = 0;
9036 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9037 OpToFold = 1;
9038 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9039 OpToFold = 2;
9040 }
9041
9042 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009043 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009044 Value *OOp = TVI->getOperand(2-OpToFold);
9045 // Avoid creating select between 2 constants unless it's selecting
9046 // between 0 and 1.
9047 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9048 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9049 InsertNewInstBefore(NewSel, SI);
9050 NewSel->takeName(TVI);
9051 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9052 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009053 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009054 }
9055 }
9056 }
9057 }
9058 }
9059
9060 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9061 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9062 !isa<Constant>(TrueVal)) {
9063 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9064 unsigned OpToFold = 0;
9065 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9066 OpToFold = 1;
9067 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9068 OpToFold = 2;
9069 }
9070
9071 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009072 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009073 Value *OOp = FVI->getOperand(2-OpToFold);
9074 // Avoid creating select between 2 constants unless it's selecting
9075 // between 0 and 1.
9076 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9077 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9078 InsertNewInstBefore(NewSel, SI);
9079 NewSel->takeName(FVI);
9080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9081 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009082 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009083 }
9084 }
9085 }
9086 }
9087 }
9088
9089 return 0;
9090}
9091
Dan Gohman81b28ce2008-09-16 18:46:06 +00009092/// visitSelectInstWithICmp - Visit a SelectInst that has an
9093/// ICmpInst as its first operand.
9094///
9095Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9096 ICmpInst *ICI) {
9097 bool Changed = false;
9098 ICmpInst::Predicate Pred = ICI->getPredicate();
9099 Value *CmpLHS = ICI->getOperand(0);
9100 Value *CmpRHS = ICI->getOperand(1);
9101 Value *TrueVal = SI.getTrueValue();
9102 Value *FalseVal = SI.getFalseValue();
9103
9104 // Check cases where the comparison is with a constant that
9105 // can be adjusted to fit the min/max idiom. We may edit ICI in
9106 // place here, so make sure the select is the only user.
9107 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009108 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009109 switch (Pred) {
9110 default: break;
9111 case ICmpInst::ICMP_ULT:
9112 case ICmpInst::ICMP_SLT: {
9113 // X < MIN ? T : F --> F
9114 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9115 return ReplaceInstUsesWith(SI, FalseVal);
9116 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009117 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009118 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9119 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9120 Pred = ICmpInst::getSwappedPredicate(Pred);
9121 CmpRHS = AdjustedRHS;
9122 std::swap(FalseVal, TrueVal);
9123 ICI->setPredicate(Pred);
9124 ICI->setOperand(1, CmpRHS);
9125 SI.setOperand(1, TrueVal);
9126 SI.setOperand(2, FalseVal);
9127 Changed = true;
9128 }
9129 break;
9130 }
9131 case ICmpInst::ICMP_UGT:
9132 case ICmpInst::ICMP_SGT: {
9133 // X > MAX ? T : F --> F
9134 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9135 return ReplaceInstUsesWith(SI, FalseVal);
9136 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009137 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009138 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9139 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9140 Pred = ICmpInst::getSwappedPredicate(Pred);
9141 CmpRHS = AdjustedRHS;
9142 std::swap(FalseVal, TrueVal);
9143 ICI->setPredicate(Pred);
9144 ICI->setOperand(1, CmpRHS);
9145 SI.setOperand(1, TrueVal);
9146 SI.setOperand(2, FalseVal);
9147 Changed = true;
9148 }
9149 break;
9150 }
9151 }
9152
Dan Gohman1975d032008-10-30 20:40:10 +00009153 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9154 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009155 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009156 if (match(TrueVal, m_ConstantInt<-1>()) &&
9157 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009158 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009159 else if (match(TrueVal, m_ConstantInt<0>()) &&
9160 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009161 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9162
Dan Gohman1975d032008-10-30 20:40:10 +00009163 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9164 // If we are just checking for a icmp eq of a single bit and zext'ing it
9165 // to an integer, then shift the bit to the appropriate place and then
9166 // cast to integer to avoid the comparison.
9167 const APInt &Op1CV = CI->getValue();
9168
9169 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9170 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9171 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009172 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009173 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009174 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009175 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009176 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009177 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009178 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009179 if (In->getType() != SI.getType())
9180 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009181 true/*SExt*/, "tmp", ICI);
9182
9183 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009184 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009185 In->getName()+".not"), *ICI);
9186
9187 return ReplaceInstUsesWith(SI, In);
9188 }
9189 }
9190 }
9191
Dan Gohman81b28ce2008-09-16 18:46:06 +00009192 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9193 // Transform (X == Y) ? X : Y -> Y
9194 if (Pred == ICmpInst::ICMP_EQ)
9195 return ReplaceInstUsesWith(SI, FalseVal);
9196 // Transform (X != Y) ? X : Y -> X
9197 if (Pred == ICmpInst::ICMP_NE)
9198 return ReplaceInstUsesWith(SI, TrueVal);
9199 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9200
9201 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9202 // Transform (X == Y) ? Y : X -> X
9203 if (Pred == ICmpInst::ICMP_EQ)
9204 return ReplaceInstUsesWith(SI, FalseVal);
9205 // Transform (X != Y) ? Y : X -> Y
9206 if (Pred == ICmpInst::ICMP_NE)
9207 return ReplaceInstUsesWith(SI, TrueVal);
9208 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9209 }
9210
9211 /// NOTE: if we wanted to, this is where to detect integer ABS
9212
9213 return Changed ? &SI : 0;
9214}
9215
Chris Lattner3d69f462004-03-12 05:52:32 +00009216Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009217 Value *CondVal = SI.getCondition();
9218 Value *TrueVal = SI.getTrueValue();
9219 Value *FalseVal = SI.getFalseValue();
9220
9221 // select true, X, Y -> X
9222 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009223 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009224 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009225
9226 // select C, X, X -> X
9227 if (TrueVal == FalseVal)
9228 return ReplaceInstUsesWith(SI, TrueVal);
9229
Chris Lattnere87597f2004-10-16 18:11:37 +00009230 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9231 return ReplaceInstUsesWith(SI, FalseVal);
9232 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9233 return ReplaceInstUsesWith(SI, TrueVal);
9234 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9235 if (isa<Constant>(TrueVal))
9236 return ReplaceInstUsesWith(SI, TrueVal);
9237 else
9238 return ReplaceInstUsesWith(SI, FalseVal);
9239 }
9240
Owen Anderson1d0be152009-08-13 21:58:54 +00009241 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009242 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009243 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009244 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009245 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009246 } else {
9247 // Change: A = select B, false, C --> A = and !B, C
9248 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009249 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009250 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009251 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009252 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009253 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009254 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009255 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009256 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009257 } else {
9258 // Change: A = select B, C, true --> A = or !B, C
9259 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009260 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009261 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009262 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009263 }
9264 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009265
9266 // select a, b, a -> a&b
9267 // select a, a, b -> a|b
9268 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009269 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009270 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009271 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009272 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009273
Chris Lattner2eefe512004-04-09 19:05:30 +00009274 // Selecting between two integer constants?
9275 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9276 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009277 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009278 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009279 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009280 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009281 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009282 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009283 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009284 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009285 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009286 }
Chris Lattner457dd822004-06-09 07:59:58 +00009287
Reid Spencere4d87aa2006-12-23 06:05:41 +00009288 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009289 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009290 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009291 // non-constant value, eliminate this whole mess. This corresponds to
9292 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009293 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009294 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009295 cast<Constant>(IC->getOperand(1))->isNullValue())
9296 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9297 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009298 isa<ConstantInt>(ICA->getOperand(1)) &&
9299 (ICA->getOperand(1) == TrueValC ||
9300 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009301 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9302 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009303 // know whether we have a icmp_ne or icmp_eq and whether the
9304 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009305 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009306 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009307 Value *V = ICA;
9308 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009309 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009310 Instruction::Xor, V, ICA->getOperand(1)), SI);
9311 return ReplaceInstUsesWith(SI, V);
9312 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009313 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009314 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009315
9316 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009317 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9318 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009319 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009320 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9321 // This is not safe in general for floating point:
9322 // consider X== -0, Y== +0.
9323 // It becomes safe if either operand is a nonzero constant.
9324 ConstantFP *CFPt, *CFPf;
9325 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9326 !CFPt->getValueAPF().isZero()) ||
9327 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9328 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009329 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009330 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009331 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009332 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009333 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009334 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009335
Reid Spencere4d87aa2006-12-23 06:05:41 +00009336 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009337 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009338 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9339 // This is not safe in general for floating point:
9340 // consider X== -0, Y== +0.
9341 // It becomes safe if either operand is a nonzero constant.
9342 ConstantFP *CFPt, *CFPf;
9343 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9344 !CFPt->getValueAPF().isZero()) ||
9345 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9346 !CFPf->getValueAPF().isZero()))
9347 return ReplaceInstUsesWith(SI, FalseVal);
9348 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009349 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00009350 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9351 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009352 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +00009353 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009354 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +00009355 }
9356
9357 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +00009358 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9359 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9360 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +00009361
Chris Lattner87875da2005-01-13 22:52:24 +00009362 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9363 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9364 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00009365 Instruction *AddOp = 0, *SubOp = 0;
9366
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009367 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9368 if (TI->getOpcode() == FI->getOpcode())
9369 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9370 return IV;
9371
9372 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9373 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009374 if ((TI->getOpcode() == Instruction::Sub &&
9375 FI->getOpcode() == Instruction::Add) ||
9376 (TI->getOpcode() == Instruction::FSub &&
9377 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009378 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009379 } else if ((FI->getOpcode() == Instruction::Sub &&
9380 TI->getOpcode() == Instruction::Add) ||
9381 (FI->getOpcode() == Instruction::FSub &&
9382 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +00009383 AddOp = TI; SubOp = FI;
9384 }
9385
9386 if (AddOp) {
9387 Value *OtherAddOp = 0;
9388 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9389 OtherAddOp = AddOp->getOperand(1);
9390 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9391 OtherAddOp = AddOp->getOperand(0);
9392 }
9393
9394 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00009395 // So at this point we know we have (Y -> OtherAddOp):
9396 // select C, (add X, Y), (sub X, Z)
9397 Value *NegVal; // Compute -Z
9398 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009399 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +00009400 } else {
9401 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +00009402 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00009403 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00009404 }
Chris Lattner97f37a42006-02-24 18:05:58 +00009405
9406 Value *NewTrueOp = OtherAddOp;
9407 Value *NewFalseOp = NegVal;
9408 if (AddOp != TI)
9409 std::swap(NewTrueOp, NewFalseOp);
9410 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +00009411 SelectInst::Create(CondVal, NewTrueOp,
9412 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +00009413
9414 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009415 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00009416 }
9417 }
9418 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009419
Chris Lattnere576b912004-04-09 23:46:01 +00009420 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00009421 if (SI.getType()->isInteger()) {
Evan Chengde621922009-03-31 20:42:45 +00009422 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9423 if (FoldI)
9424 return FoldI;
Chris Lattnere576b912004-04-09 23:46:01 +00009425 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00009426
9427 if (BinaryOperator::isNot(CondVal)) {
9428 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9429 SI.setOperand(1, FalseVal);
9430 SI.setOperand(2, TrueVal);
9431 return &SI;
9432 }
9433
Chris Lattner3d69f462004-03-12 05:52:32 +00009434 return 0;
9435}
9436
Dan Gohmaneee962e2008-04-10 18:43:06 +00009437/// EnforceKnownAlignment - If the specified pointer points to an object that
9438/// we control, modify the object's alignment to PrefAlign. This isn't
9439/// often possible though. If alignment is important, a more reliable approach
9440/// is to simply align all global variables and allocation instructions to
9441/// their preferred alignment from the beginning.
9442///
9443static unsigned EnforceKnownAlignment(Value *V,
9444 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00009445
Dan Gohmaneee962e2008-04-10 18:43:06 +00009446 User *U = dyn_cast<User>(V);
9447 if (!U) return Align;
9448
Dan Gohmanca178902009-07-17 20:47:02 +00009449 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009450 default: break;
9451 case Instruction::BitCast:
9452 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9453 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +00009454 // If all indexes are zero, it is just the alignment of the base pointer.
9455 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +00009456 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +00009457 if (!isa<Constant>(*i) ||
9458 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +00009459 AllZeroOperands = false;
9460 break;
9461 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00009462
9463 if (AllZeroOperands) {
9464 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +00009465 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +00009466 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009467 break;
Chris Lattner95a959d2006-03-06 20:18:44 +00009468 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009469 }
9470
9471 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9472 // If there is a large requested alignment and we can, bump up the alignment
9473 // of the global.
9474 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009475 if (GV->getAlignment() >= PrefAlign)
9476 Align = GV->getAlignment();
9477 else {
9478 GV->setAlignment(PrefAlign);
9479 Align = PrefAlign;
9480 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009481 }
9482 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9483 // If there is a requested alignment and if this is an alloca, round up. We
9484 // don't do this for malloc, because some systems can't respect the request.
9485 if (isa<AllocaInst>(AI)) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +00009486 if (AI->getAlignment() >= PrefAlign)
9487 Align = AI->getAlignment();
9488 else {
9489 AI->setAlignment(PrefAlign);
9490 Align = PrefAlign;
9491 }
Dan Gohmaneee962e2008-04-10 18:43:06 +00009492 }
9493 }
9494
9495 return Align;
9496}
9497
9498/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9499/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9500/// and it is more than the alignment of the ultimate object, see if we can
9501/// increase the alignment of the ultimate object, making this check succeed.
9502unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9503 unsigned PrefAlign) {
9504 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9505 sizeof(PrefAlign) * CHAR_BIT;
9506 APInt Mask = APInt::getAllOnesValue(BitWidth);
9507 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9508 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9509 unsigned TrailZ = KnownZero.countTrailingOnes();
9510 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9511
9512 if (PrefAlign > Align)
9513 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9514
9515 // We don't need to make any adjustment.
9516 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +00009517}
9518
Chris Lattnerf497b022008-01-13 23:50:23 +00009519Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +00009520 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +00009521 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +00009522 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009523 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +00009524
9525 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009526 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009527 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +00009528 return MI;
9529 }
9530
9531 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9532 // load/store.
9533 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9534 if (MemOpLength == 0) return 0;
9535
Chris Lattner37ac6082008-01-14 00:28:35 +00009536 // Source and destination pointer types are always "i8*" for intrinsic. See
9537 // if the size is something we can handle with a single primitive load/store.
9538 // A single load+store correctly handles overlapping memory in the memmove
9539 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00009540 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009541 if (Size == 0) return MI; // Delete this mem transfer.
9542
9543 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00009544 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00009545
Chris Lattner37ac6082008-01-14 00:28:35 +00009546 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +00009547 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +00009548 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00009549
9550 // Memcpy forces the use of i8* for the source and destination. That means
9551 // that if you're using memcpy to move one double around, you'll get a cast
9552 // from double* to i8*. We'd much rather use a double load+store rather than
9553 // an i64 load+store, here because this improves the odds that the source or
9554 // dest address will be promotable. See if we can find a better type than the
9555 // integer datatype.
9556 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9557 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009558 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009559 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9560 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +00009561 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +00009562 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9563 if (STy->getNumElements() == 1)
9564 SrcETy = STy->getElementType(0);
9565 else
9566 break;
9567 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9568 if (ATy->getNumElements() == 1)
9569 SrcETy = ATy->getElementType();
9570 else
9571 break;
9572 } else
9573 break;
9574 }
9575
Dan Gohman8f8e2692008-05-23 01:52:21 +00009576 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +00009577 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +00009578 }
9579 }
9580
9581
Chris Lattnerf497b022008-01-13 23:50:23 +00009582 // If the memcpy/memmove provides better alignment info than we can
9583 // infer, use it.
9584 SrcAlign = std::max(SrcAlign, CopyAlign);
9585 DstAlign = std::max(DstAlign, CopyAlign);
9586
9587 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9588 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00009589 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9590 InsertNewInstBefore(L, *MI);
9591 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9592
9593 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009594 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +00009595 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00009596}
Chris Lattner3d69f462004-03-12 05:52:32 +00009597
Chris Lattner69ea9d22008-04-30 06:39:11 +00009598Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9599 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009600 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +00009601 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +00009602 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009603 return MI;
9604 }
9605
9606 // Extract the length and alignment and fill if they are constant.
9607 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9608 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +00009609 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +00009610 return 0;
9611 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +00009612 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +00009613
9614 // If the length is zero, this is a no-op
9615 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9616
9617 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9618 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009619 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +00009620
9621 Value *Dest = MI->getDest();
Owen Andersondebcb012009-07-29 22:17:13 +00009622 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009623
9624 // Alignment 0 is identity for alignment 1 for memset, but not store.
9625 if (Alignment == 0) Alignment = 1;
9626
9627 // Extract the fill value and store.
9628 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +00009629 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +00009630 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +00009631
9632 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +00009633 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +00009634 return MI;
9635 }
9636
9637 return 0;
9638}
9639
9640
Chris Lattner8b0ea312006-01-13 20:11:04 +00009641/// visitCallInst - CallInst simplification. This mostly only handles folding
9642/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9643/// the heavy lifting.
9644///
Chris Lattner9fe38862003-06-19 17:00:31 +00009645Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraab6ec42009-05-13 17:39:14 +00009646 // If the caller function is nounwind, mark the call as nounwind, even if the
9647 // callee isn't.
9648 if (CI.getParent()->getParent()->doesNotThrow() &&
9649 !CI.doesNotThrow()) {
9650 CI.setDoesNotThrow();
9651 return &CI;
9652 }
9653
Chris Lattner8b0ea312006-01-13 20:11:04 +00009654 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9655 if (!II) return visitCallSite(&CI);
9656
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009657 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9658 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00009659 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009660 bool Changed = false;
9661
9662 // memmove/cpy/set of zero bytes is a noop.
9663 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9664 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9665
Chris Lattner35b9e482004-10-12 04:52:52 +00009666 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00009667 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009668 // Replace the instruction with just byte operations. We would
9669 // transform other cases to loads/stores, but we don't know if
9670 // alignment is sufficient.
9671 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009672 }
9673
Chris Lattner35b9e482004-10-12 04:52:52 +00009674 // If we have a memmove and the source operation is a constant global,
9675 // then the source and dest pointers can't alias, so we can change this
9676 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00009677 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00009678 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9679 if (GVSrc->isConstant()) {
9680 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +00009681 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9682 const Type *Tys[1];
9683 Tys[0] = CI.getOperand(3)->getType();
9684 CI.setOperand(0,
9685 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +00009686 Changed = true;
9687 }
Chris Lattnera935db82008-05-28 05:30:41 +00009688
9689 // memmove(x,x,size) -> noop.
9690 if (MMI->getSource() == MMI->getDest())
9691 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +00009692 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009693
Chris Lattner95a959d2006-03-06 20:18:44 +00009694 // If we can determine a pointer alignment that is bigger than currently
9695 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +00009696 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00009697 if (Instruction *I = SimplifyMemTransfer(MI))
9698 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +00009699 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9700 if (Instruction *I = SimplifyMemSet(MSI))
9701 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00009702 }
9703
Chris Lattner8b0ea312006-01-13 20:11:04 +00009704 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +00009705 }
9706
9707 switch (II->getIntrinsicID()) {
9708 default: break;
9709 case Intrinsic::bswap:
9710 // bswap(bswap(x)) -> x
9711 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9712 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9713 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9714 break;
9715 case Intrinsic::ppc_altivec_lvx:
9716 case Intrinsic::ppc_altivec_lvxl:
9717 case Intrinsic::x86_sse_loadu_ps:
9718 case Intrinsic::x86_sse2_loadu_pd:
9719 case Intrinsic::x86_sse2_loadu_dq:
9720 // Turn PPC lvx -> load if the pointer is known aligned.
9721 // Turn X86 loadups -> load if the pointer is known aligned.
9722 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9723 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Andersondebcb012009-07-29 22:17:13 +00009724 PointerType::getUnqual(II->getType()),
Chris Lattner0521e3c2008-06-18 04:33:20 +00009725 CI);
9726 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +00009727 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009728 break;
9729 case Intrinsic::ppc_altivec_stvx:
9730 case Intrinsic::ppc_altivec_stvxl:
9731 // Turn stvx -> store if the pointer is known aligned.
9732 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9733 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009734 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009735 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9736 return new StoreInst(II->getOperand(1), Ptr);
9737 }
9738 break;
9739 case Intrinsic::x86_sse_storeu_ps:
9740 case Intrinsic::x86_sse2_storeu_pd:
9741 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +00009742 // Turn X86 storeu -> store if the pointer is known aligned.
9743 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9744 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +00009745 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner0521e3c2008-06-18 04:33:20 +00009746 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9747 return new StoreInst(II->getOperand(2), Ptr);
9748 }
9749 break;
9750
9751 case Intrinsic::x86_sse_cvttss2si: {
9752 // These intrinsics only demands the 0th element of its input vector. If
9753 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +00009754 unsigned VWidth =
9755 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9756 APInt DemandedElts(VWidth, 1);
9757 APInt UndefElts(VWidth, 0);
9758 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +00009759 UndefElts)) {
9760 II->setOperand(1, V);
9761 return II;
9762 }
9763 break;
9764 }
9765
9766 case Intrinsic::ppc_altivec_vperm:
9767 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9768 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9769 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +00009770
Chris Lattner0521e3c2008-06-18 04:33:20 +00009771 // Check that all of the elements are integer constants or undefs.
9772 bool AllEltsOk = true;
9773 for (unsigned i = 0; i != 16; ++i) {
9774 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9775 !isa<UndefValue>(Mask->getOperand(i))) {
9776 AllEltsOk = false;
9777 break;
9778 }
9779 }
9780
9781 if (AllEltsOk) {
9782 // Cast the input vectors to byte vectors.
9783 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9784 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009785 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009786
Chris Lattner0521e3c2008-06-18 04:33:20 +00009787 // Only extract each element once.
9788 Value *ExtractedElts[32];
9789 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9790
Chris Lattnere2ed0572006-04-06 19:19:17 +00009791 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +00009792 if (isa<UndefValue>(Mask->getOperand(i)))
9793 continue;
9794 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9795 Idx &= 31; // Match the hardware behavior.
9796
9797 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009798 ExtractedElts[Idx] =
9799 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9800 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9801 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009802 }
Chris Lattnere2ed0572006-04-06 19:19:17 +00009803
Chris Lattner0521e3c2008-06-18 04:33:20 +00009804 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009805 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9806 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9807 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00009808 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009809 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00009810 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009811 }
9812 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +00009813
Chris Lattner0521e3c2008-06-18 04:33:20 +00009814 case Intrinsic::stackrestore: {
9815 // If the save is right next to the restore, remove the restore. This can
9816 // happen when variable allocas are DCE'd.
9817 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9818 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9819 BasicBlock::iterator BI = SS;
9820 if (&*++BI == II)
9821 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00009822 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009823 }
9824
9825 // Scan down this block to see if there is another stack restore in the
9826 // same block without an intervening call/alloca.
9827 BasicBlock::iterator BI = II;
9828 TerminatorInst *TI = II->getParent()->getTerminator();
9829 bool CannotRemove = false;
9830 for (++BI; &*BI != TI; ++BI) {
9831 if (isa<AllocaInst>(BI)) {
9832 CannotRemove = true;
9833 break;
9834 }
Chris Lattneraa0bf522008-06-25 05:59:28 +00009835 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9836 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9837 // If there is a stackrestore below this one, remove this one.
9838 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9839 return EraseInstFromFunction(CI);
9840 // Otherwise, ignore the intrinsic.
9841 } else {
9842 // If we found a non-intrinsic call, we can't remove the stack
9843 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00009844 CannotRemove = true;
9845 break;
9846 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009847 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00009848 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00009849
9850 // If the stack restore is in a return/unwind block and if there are no
9851 // allocas or calls between the restore and the return, nuke the restore.
9852 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9853 return EraseInstFromFunction(CI);
9854 break;
9855 }
Chris Lattner35b9e482004-10-12 04:52:52 +00009856 }
9857
Chris Lattner8b0ea312006-01-13 20:11:04 +00009858 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009859}
9860
9861// InvokeInst simplification
9862//
9863Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00009864 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00009865}
9866
Dale Johannesenda30ccb2008-04-25 21:16:07 +00009867/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9868/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +00009869static bool isSafeToEliminateVarargsCast(const CallSite CS,
9870 const CastInst * const CI,
9871 const TargetData * const TD,
9872 const int ix) {
9873 if (!CI->isLosslessCast())
9874 return false;
9875
9876 // The size of ByVal arguments is derived from the type, so we
9877 // can't change to a type with a different size. If the size were
9878 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +00009879 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009880 return true;
9881
9882 const Type* SrcTy =
9883 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9884 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9885 if (!SrcTy->isSized() || !DstTy->isSized())
9886 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009887 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +00009888 return false;
9889 return true;
9890}
9891
Chris Lattnera44d8a22003-10-07 22:32:43 +00009892// visitCallSite - Improvements for call and invoke instructions.
9893//
9894Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00009895 bool Changed = false;
9896
9897 // If the callee is a constexpr cast of a function, attempt to move the cast
9898 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00009899 if (transformConstExprCastCall(CS)) return 0;
9900
Chris Lattner6c266db2003-10-07 22:54:13 +00009901 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00009902
Chris Lattner08b22ec2005-05-13 07:09:09 +00009903 if (Function *CalleeF = dyn_cast<Function>(Callee))
9904 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9905 Instruction *OldCall = CS.getInstruction();
9906 // If the call and callee calling conventions don't match, this call must
9907 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +00009908 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009909 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Owen Andersond672ecb2009-07-03 00:17:18 +00009910 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00009911 if (!OldCall->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009912 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +00009913 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9914 return EraseInstFromFunction(*OldCall);
9915 return 0;
9916 }
9917
Chris Lattner17be6352004-10-18 02:59:09 +00009918 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9919 // This instruction is not reachable, just remove it. We insert a store to
9920 // undef so that we know that this code is not reachable, despite the fact
9921 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +00009922 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +00009923 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
Chris Lattner17be6352004-10-18 02:59:09 +00009924 CS.getInstruction());
9925
9926 if (!CS.getInstruction()->use_empty())
9927 CS.getInstruction()->
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009928 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009929
9930 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9931 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +00009932 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +00009933 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00009934 }
Chris Lattner17be6352004-10-18 02:59:09 +00009935 return EraseInstFromFunction(*CS.getInstruction());
9936 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009937
Duncan Sandscdb6d922007-09-17 10:26:40 +00009938 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9939 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9940 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9941 return transformCallThroughTrampoline(CS);
9942
Chris Lattner6c266db2003-10-07 22:54:13 +00009943 const PointerType *PTy = cast<PointerType>(Callee->getType());
9944 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9945 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +00009946 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +00009947 // See if we can optimize any arguments passed through the varargs area of
9948 // the call.
9949 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +00009950 E = CS.arg_end(); I != E; ++I, ++ix) {
9951 CastInst *CI = dyn_cast<CastInst>(*I);
9952 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9953 *I = CI->getOperand(0);
9954 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +00009955 }
Dale Johannesen1f530a52008-04-23 18:34:37 +00009956 }
Chris Lattner6c266db2003-10-07 22:54:13 +00009957 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009958
Duncan Sandsf0c33542007-12-19 21:13:37 +00009959 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00009960 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00009961 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00009962 Changed = true;
9963 }
9964
Chris Lattner6c266db2003-10-07 22:54:13 +00009965 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00009966}
9967
Chris Lattner9fe38862003-06-19 17:00:31 +00009968// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9969// attempt to move the cast to the arguments of the call/invoke.
9970//
9971bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9972 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9973 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00009974 if (CE->getOpcode() != Instruction::BitCast ||
9975 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00009976 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00009977 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00009978 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +00009979 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +00009980
9981 // Okay, this is a cast from a function to a different type. Unless doing so
9982 // would cause a type conversion of one of our arguments, change this call to
9983 // be a direct call with arguments casted to the appropriate types.
9984 //
9985 const FunctionType *FT = Callee->getFunctionType();
9986 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009987 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +00009988
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009989 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +00009990 return false; // TODO: Handle multiple return values.
9991
Chris Lattnerf78616b2004-01-14 06:06:08 +00009992 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009993 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +00009994 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +00009995 // Conversion is ok if changing from one pointer type to another or from
9996 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009997 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +00009998 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009999 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010000 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010001 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010002
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010003 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010004 // void -> non-void is handled specially
Owen Anderson1d0be152009-08-13 21:58:54 +000010005 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010006 return false; // Cannot transform this return value.
10007
Chris Lattner58d74912008-03-12 17:45:29 +000010008 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010009 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010010 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010011 return false; // Attribute not compatible with transformed value.
10012 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010013
Chris Lattnerf78616b2004-01-14 06:06:08 +000010014 // If the callsite is an invoke instruction, and the return value is used by
10015 // a PHI node in a successor, we cannot change the return type of the call
10016 // because there is no place to put the cast instruction (without breaking
10017 // the critical edge). Bail out in this case.
10018 if (!Caller->use_empty())
10019 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10020 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10021 UI != E; ++UI)
10022 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10023 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010024 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010025 return false;
10026 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010027
10028 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10029 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010030
Chris Lattner9fe38862003-06-19 17:00:31 +000010031 CallSite::arg_iterator AI = CS.arg_begin();
10032 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10033 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010034 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010035
10036 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010037 return false; // Cannot transform this parameter value.
10038
Devang Patel19c87462008-09-26 22:53:05 +000010039 if (CallerPAL.getParamAttributes(i + 1)
10040 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010041 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010042
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010043 // Converting from one pointer type to another or between a pointer and an
10044 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010045 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010046 (TD && ((isa<PointerType>(ParamTy) ||
10047 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10048 (isa<PointerType>(ActTy) ||
10049 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010050 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010051 }
10052
10053 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010054 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010055 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010056
Chris Lattner58d74912008-03-12 17:45:29 +000010057 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10058 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010059 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010060 // won't be dropping them. Check that these extra arguments have attributes
10061 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010062 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10063 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010064 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010065 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010066 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010067 return false;
10068 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010069
Chris Lattner9fe38862003-06-19 17:00:31 +000010070 // Okay, we decided that this is a safe thing to do: go ahead and start
10071 // inserting cast instructions as necessary...
10072 std::vector<Value*> Args;
10073 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010074 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010075 attrVec.reserve(NumCommonArgs);
10076
10077 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010078 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010079
10080 // If the return value is not being used, the type may not be compatible
10081 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010082 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010083
10084 // Add the new return attributes.
10085 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010086 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010087
10088 AI = CS.arg_begin();
10089 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10090 const Type *ParamTy = FT->getParamType(i);
10091 if ((*AI)->getType() == ParamTy) {
10092 Args.push_back(*AI);
10093 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010094 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010095 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010096 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010097 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010098
10099 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010100 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010101 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010102 }
10103
10104 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010105 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010106 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010107 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010108
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010109 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010110 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010111 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010112 errs() << "WARNING: While resolving call to function '"
10113 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010114 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010115 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010116 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10117 const Type *PTy = getPromotedType((*AI)->getType());
10118 if (PTy != (*AI)->getType()) {
10119 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010120 Instruction::CastOps opcode =
10121 CastInst::getCastOpcode(*AI, false, PTy, false);
10122 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010123 } else {
10124 Args.push_back(*AI);
10125 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010126
Duncan Sandse1e520f2008-01-13 08:02:44 +000010127 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010128 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010129 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010130 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010131 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010132 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010133
Devang Patel19c87462008-09-26 22:53:05 +000010134 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10135 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10136
Owen Anderson1d0be152009-08-13 21:58:54 +000010137 if (NewRetTy == Type::getVoidTy(*Context))
Chris Lattner6934a042007-02-11 01:23:03 +000010138 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010139
Eric Christophera66297a2009-07-25 02:45:27 +000010140 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10141 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010142
Chris Lattner9fe38862003-06-19 17:00:31 +000010143 Instruction *NC;
10144 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010145 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010146 Args.begin(), Args.end(),
10147 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010148 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010149 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010150 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010151 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10152 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010153 CallInst *CI = cast<CallInst>(Caller);
10154 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010155 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010156 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010157 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010158 }
10159
Chris Lattner6934a042007-02-11 01:23:03 +000010160 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010161 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010162 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010163 if (NV->getType() != Type::getVoidTy(*Context)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010164 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010165 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010166 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000010167
10168 // If this is an invoke instruction, we should insert it after the first
10169 // non-phi, instruction in the normal successor block.
10170 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000010171 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000010172 InsertNewInstBefore(NC, *I);
10173 } else {
10174 // Otherwise, it's a call, just insert cast right after the call instr
10175 InsertNewInstBefore(NC, *Caller);
10176 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000010177 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010178 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010179 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000010180 }
10181 }
10182
Owen Anderson1d0be152009-08-13 21:58:54 +000010183 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000010184 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +000010185 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010186 Worklist.Remove(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000010187 return true;
10188}
10189
Duncan Sandscdb6d922007-09-17 10:26:40 +000010190// transformCallThroughTrampoline - Turn a call to a function created by the
10191// init_trampoline intrinsic into a direct call to the underlying function.
10192//
10193Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10194 Value *Callee = CS.getCalledValue();
10195 const PointerType *PTy = cast<PointerType>(Callee->getType());
10196 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000010197 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010198
10199 // If the call already has the 'nest' attribute somewhere then give up -
10200 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000010201 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010202 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010203
10204 IntrinsicInst *Tramp =
10205 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10206
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000010207 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010208 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10209 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10210
Devang Patel05988662008-09-25 21:00:45 +000010211 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000010212 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010213 unsigned NestIdx = 1;
10214 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000010215 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010216
10217 // Look for a parameter marked with the 'nest' attribute.
10218 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10219 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000010220 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000010221 // Record the parameter type and any other attributes.
10222 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000010223 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010224 break;
10225 }
10226
10227 if (NestTy) {
10228 Instruction *Caller = CS.getInstruction();
10229 std::vector<Value*> NewArgs;
10230 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10231
Devang Patel05988662008-09-25 21:00:45 +000010232 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000010233 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010234
Duncan Sandscdb6d922007-09-17 10:26:40 +000010235 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010236 // mean appending it. Likewise for attributes.
10237
Devang Patel19c87462008-09-26 22:53:05 +000010238 // Add any result attributes.
10239 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000010240 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010241
Duncan Sandscdb6d922007-09-17 10:26:40 +000010242 {
10243 unsigned Idx = 1;
10244 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10245 do {
10246 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010247 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010248 Value *NestVal = Tramp->getOperand(3);
10249 if (NestVal->getType() != NestTy)
10250 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10251 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000010252 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010253 }
10254
10255 if (I == E)
10256 break;
10257
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010258 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010259 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000010260 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010261 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000010262 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000010263
10264 ++Idx, ++I;
10265 } while (1);
10266 }
10267
Devang Patel19c87462008-09-26 22:53:05 +000010268 // Add any function attributes.
10269 if (Attributes Attr = Attrs.getFnAttributes())
10270 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10271
Duncan Sandscdb6d922007-09-17 10:26:40 +000010272 // The trampoline may have been bitcast to a bogus type (FTy).
10273 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010274 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010275
Duncan Sandscdb6d922007-09-17 10:26:40 +000010276 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000010277 NewTypes.reserve(FTy->getNumParams()+1);
10278
Duncan Sandscdb6d922007-09-17 10:26:40 +000010279 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010280 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010281 {
10282 unsigned Idx = 1;
10283 FunctionType::param_iterator I = FTy->param_begin(),
10284 E = FTy->param_end();
10285
10286 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010287 if (Idx == NestIdx)
10288 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010289 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010290
10291 if (I == E)
10292 break;
10293
Duncan Sandsb0c9b932008-01-14 19:52:09 +000010294 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000010295 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010296
10297 ++Idx, ++I;
10298 } while (1);
10299 }
10300
10301 // Replace the trampoline call with a direct call. Let the generic
10302 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000010303 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000010304 FTy->isVarArg());
10305 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000010306 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000010307 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000010308 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000010309 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10310 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000010311
10312 Instruction *NewCaller;
10313 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010314 NewCaller = InvokeInst::Create(NewCallee,
10315 II->getNormalDest(), II->getUnwindDest(),
10316 NewArgs.begin(), NewArgs.end(),
10317 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010318 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010319 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010320 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010321 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10322 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010323 if (cast<CallInst>(Caller)->isTailCall())
10324 cast<CallInst>(NewCaller)->setTailCall();
10325 cast<CallInst>(NewCaller)->
10326 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010327 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010328 }
Owen Anderson1d0be152009-08-13 21:58:54 +000010329 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
Duncan Sandscdb6d922007-09-17 10:26:40 +000010330 Caller->replaceAllUsesWith(NewCaller);
10331 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000010332 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010333 return 0;
10334 }
10335 }
10336
10337 // Replace the trampoline call with a direct call. Since there is no 'nest'
10338 // parameter, there is no need to adjust the argument list. Let the generic
10339 // code sort out any function type mismatches.
10340 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000010341 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000010342 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000010343 CS.setCalledFunction(NewCallee);
10344 return CS.getInstruction();
10345}
10346
Chris Lattner7da52b22006-11-01 04:51:18 +000010347/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10348/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10349/// and a single binop.
10350Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10351 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010352 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000010353 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010354 Value *LHSVal = FirstInst->getOperand(0);
10355 Value *RHSVal = FirstInst->getOperand(1);
10356
10357 const Type *LHSType = LHSVal->getType();
10358 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000010359
10360 // Scan to see if all operands are the same opcode, all have one use, and all
10361 // kill their operands (i.e. the operands have one use).
Chris Lattner05f18922008-12-01 02:34:36 +000010362 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000010363 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000010364 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000010365 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000010366 // types or GEP's with different index types.
10367 I->getOperand(0)->getType() != LHSType ||
10368 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000010369 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010370
10371 // If they are CmpInst instructions, check their predicates
10372 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10373 if (cast<CmpInst>(I)->getPredicate() !=
10374 cast<CmpInst>(FirstInst)->getPredicate())
10375 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010376
10377 // Keep track of which operand needs a phi node.
10378 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10379 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000010380 }
10381
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010382 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000010383
Chris Lattner7da52b22006-11-01 04:51:18 +000010384 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000010385 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000010386 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010387 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010388 NewLHS = PHINode::Create(LHSType,
10389 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010390 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10391 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010392 InsertNewInstBefore(NewLHS, PN);
10393 LHSVal = NewLHS;
10394 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010395
10396 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010397 NewRHS = PHINode::Create(RHSType,
10398 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010399 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10400 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000010401 InsertNewInstBefore(NewRHS, PN);
10402 RHSVal = NewRHS;
10403 }
10404
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010405 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000010406 if (NewLHS || NewRHS) {
10407 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10408 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10409 if (NewLHS) {
10410 Value *NewInLHS = InInst->getOperand(0);
10411 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10412 }
10413 if (NewRHS) {
10414 Value *NewInRHS = InInst->getOperand(1);
10415 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10416 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000010417 }
10418 }
10419
Chris Lattner7da52b22006-11-01 04:51:18 +000010420 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010421 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000010422 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010423 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000010424 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000010425}
10426
Chris Lattner05f18922008-12-01 02:34:36 +000010427Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10428 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10429
10430 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10431 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000010432 // This is true if all GEP bases are allocas and if all indices into them are
10433 // constants.
10434 bool AllBasePointersAreAllocas = true;
Chris Lattner05f18922008-12-01 02:34:36 +000010435
10436 // Scan to see if all operands are the same opcode, all have one use, and all
10437 // kill their operands (i.e. the operands have one use).
10438 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10439 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10440 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10441 GEP->getNumOperands() != FirstInst->getNumOperands())
10442 return 0;
10443
Chris Lattner36d3e322009-02-21 00:46:50 +000010444 // Keep track of whether or not all GEPs are of alloca pointers.
10445 if (AllBasePointersAreAllocas &&
10446 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10447 !GEP->hasAllConstantIndices()))
10448 AllBasePointersAreAllocas = false;
10449
Chris Lattner05f18922008-12-01 02:34:36 +000010450 // Compare the operand lists.
10451 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10452 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10453 continue;
10454
10455 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10456 // if one of the PHIs has a constant for the index. The index may be
10457 // substantially cheaper to compute for the constants, so making it a
10458 // variable index could pessimize the path. This also handles the case
10459 // for struct indices, which must always be constant.
10460 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10461 isa<ConstantInt>(GEP->getOperand(op)))
10462 return 0;
10463
10464 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10465 return 0;
10466 FixedOperands[op] = 0; // Needs a PHI.
10467 }
10468 }
10469
Chris Lattner36d3e322009-02-21 00:46:50 +000010470 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000010471 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000010472 // offset calculation, but all the predecessors will have to materialize the
10473 // stack address into a register anyway. We'd actually rather *clone* the
10474 // load up into the predecessors so that we have a load of a gep of an alloca,
10475 // which can usually all be folded into the load.
10476 if (AllBasePointersAreAllocas)
10477 return 0;
10478
Chris Lattner05f18922008-12-01 02:34:36 +000010479 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10480 // that is variable.
10481 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10482
10483 bool HasAnyPHIs = false;
10484 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10485 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10486 Value *FirstOp = FirstInst->getOperand(i);
10487 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10488 FirstOp->getName()+".pn");
10489 InsertNewInstBefore(NewPN, PN);
10490
10491 NewPN->reserveOperandSpace(e);
10492 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10493 OperandPhis[i] = NewPN;
10494 FixedOperands[i] = NewPN;
10495 HasAnyPHIs = true;
10496 }
10497
10498
10499 // Add all operands to the new PHIs.
10500 if (HasAnyPHIs) {
10501 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10502 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10503 BasicBlock *InBB = PN.getIncomingBlock(i);
10504
10505 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10506 if (PHINode *OpPhi = OperandPhis[op])
10507 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10508 }
10509 }
10510
10511 Value *Base = FixedOperands[0];
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010512 GetElementPtrInst *GEP =
10513 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10514 FixedOperands.end());
10515 if (cast<GEPOperator>(FirstInst)->isInBounds())
10516 cast<GEPOperator>(GEP)->setIsInBounds(true);
10517 return GEP;
Chris Lattner05f18922008-12-01 02:34:36 +000010518}
10519
10520
Chris Lattner21550882009-02-23 05:56:17 +000010521/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10522/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000010523/// obvious the value of the load is not changed from the point of the load to
10524/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010525///
10526/// Finally, it is safe, but not profitable, to sink a load targetting a
10527/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10528/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000010529static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000010530 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10531
10532 for (++BBI; BBI != E; ++BBI)
10533 if (BBI->mayWriteToMemory())
10534 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010535
10536 // Check for non-address taken alloca. If not address-taken already, it isn't
10537 // profitable to do this xform.
10538 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10539 bool isAddressTaken = false;
10540 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10541 UI != E; ++UI) {
10542 if (isa<LoadInst>(UI)) continue;
10543 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10544 // If storing TO the alloca, then the address isn't taken.
10545 if (SI->getOperand(1) == AI) continue;
10546 }
10547 isAddressTaken = true;
10548 break;
10549 }
10550
Chris Lattner36d3e322009-02-21 00:46:50 +000010551 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000010552 return false;
10553 }
10554
Chris Lattner36d3e322009-02-21 00:46:50 +000010555 // If this load is a load from a GEP with a constant offset from an alloca,
10556 // then we don't want to sink it. In its present form, it will be
10557 // load [constant stack offset]. Sinking it will cause us to have to
10558 // materialize the stack addresses in each predecessor in a register only to
10559 // do a shared load from register in the successor.
10560 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10561 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10562 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10563 return false;
10564
Chris Lattner76c73142006-11-01 07:13:54 +000010565 return true;
10566}
10567
Chris Lattner9fe38862003-06-19 17:00:31 +000010568
Chris Lattnerbac32862004-11-14 19:13:23 +000010569// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10570// operator and they all are only used by the PHI, PHI together their
10571// inputs, and do the operation once, to the result of the PHI.
10572Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10573 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10574
10575 // Scan the instruction, looking for input operations that can be folded away.
10576 // If all input operands to the phi are the same instruction (e.g. a cast from
10577 // the same type or "+42") we can pull the operation through the PHI, reducing
10578 // code size and simplifying code.
10579 Constant *ConstantOp = 0;
10580 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +000010581 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +000010582 if (isa<CastInst>(FirstInst)) {
10583 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +000010584 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010585 // Can fold binop, compare or shift here if the RHS is a constant,
10586 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000010587 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000010588 if (ConstantOp == 0)
10589 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +000010590 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10591 isVolatile = LI->isVolatile();
10592 // We can't sink the load if the loaded value could be modified between the
10593 // load and the PHI.
10594 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010595 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010596 return 0;
Chris Lattner71042962008-07-08 17:18:32 +000010597
10598 // If the PHI is of volatile loads and the load block has multiple
10599 // successors, sinking it would remove a load of the volatile value from
10600 // the path through the other successor.
10601 if (isVolatile &&
10602 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10603 return 0;
10604
Chris Lattner9c080502006-11-01 07:43:41 +000010605 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner05f18922008-12-01 02:34:36 +000010606 return FoldPHIArgGEPIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000010607 } else {
10608 return 0; // Cannot fold this operation.
10609 }
10610
10611 // Check to see if all arguments are the same operation.
10612 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10613 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10614 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +000010615 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000010616 return 0;
10617 if (CastSrcTy) {
10618 if (I->getOperand(0)->getType() != CastSrcTy)
10619 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +000010620 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000010621 // We can't sink the load if the loaded value could be modified between
10622 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +000010623 if (LI->isVolatile() != isVolatile ||
10624 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattner36d3e322009-02-21 00:46:50 +000010625 !isSafeAndProfitableToSinkLoad(LI))
Chris Lattner76c73142006-11-01 07:13:54 +000010626 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010627
Chris Lattner71042962008-07-08 17:18:32 +000010628 // If the PHI is of volatile loads and the load block has multiple
10629 // successors, sinking it would remove a load of the volatile value from
10630 // the path through the other successor.
Chris Lattner40700fe2008-04-29 17:28:22 +000010631 if (isVolatile &&
10632 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10633 return 0;
Chris Lattner40700fe2008-04-29 17:28:22 +000010634
Chris Lattnerbac32862004-11-14 19:13:23 +000010635 } else if (I->getOperand(1) != ConstantOp) {
10636 return 0;
10637 }
10638 }
10639
10640 // Okay, they are all the same operation. Create a new PHI node of the
10641 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000010642 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10643 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000010644 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000010645
10646 Value *InVal = FirstInst->getOperand(0);
10647 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000010648
10649 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000010650 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10651 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10652 if (NewInVal != InVal)
10653 InVal = 0;
10654 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10655 }
10656
10657 Value *PhiVal;
10658 if (InVal) {
10659 // The new PHI unions all of the same values together. This is really
10660 // common, so we handle it intelligently here for compile-time speed.
10661 PhiVal = InVal;
10662 delete NewPN;
10663 } else {
10664 InsertNewInstBefore(NewPN, PN);
10665 PhiVal = NewPN;
10666 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010667
Chris Lattnerbac32862004-11-14 19:13:23 +000010668 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +000010669 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010670 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattner54545ac2008-04-29 17:13:43 +000010671 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010672 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010673 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Dan Gohman1c8a23c2009-08-25 23:17:54 +000010674 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +000010675 PhiVal, ConstantOp);
Chris Lattner54545ac2008-04-29 17:13:43 +000010676 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10677
10678 // If this was a volatile load that we are merging, make sure to loop through
10679 // and mark all the input loads as non-volatile. If we don't do this, we will
10680 // insert a new volatile load and the old ones will not be deletable.
10681 if (isVolatile)
10682 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10683 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10684
10685 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +000010686}
Chris Lattnera1be5662002-05-02 17:06:02 +000010687
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010688/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10689/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010690static bool DeadPHICycle(PHINode *PN,
10691 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010692 if (PN->use_empty()) return true;
10693 if (!PN->hasOneUse()) return false;
10694
10695 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000010696 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010697 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000010698
10699 // Don't scan crazily complex things.
10700 if (PotentiallyDeadPHIs.size() == 16)
10701 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010702
10703 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10704 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010705
Chris Lattnera3fd1c52005-01-17 05:10:15 +000010706 return false;
10707}
10708
Chris Lattnercf5008a2007-11-06 21:52:06 +000010709/// PHIsEqualValue - Return true if this phi node is always equal to
10710/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10711/// z = some value; x = phi (y, z); y = phi (x, z)
10712static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10713 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10714 // See if we already saw this PHI node.
10715 if (!ValueEqualPHIs.insert(PN))
10716 return true;
10717
10718 // Don't scan crazily complex things.
10719 if (ValueEqualPHIs.size() == 16)
10720 return false;
10721
10722 // Scan the operands to see if they are either phi nodes or are equal to
10723 // the value.
10724 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10725 Value *Op = PN->getIncomingValue(i);
10726 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10727 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10728 return false;
10729 } else if (Op != NonPhiInVal)
10730 return false;
10731 }
10732
10733 return true;
10734}
10735
10736
Chris Lattner473945d2002-05-06 18:06:38 +000010737// PHINode simplification
10738//
Chris Lattner7e708292002-06-25 16:13:24 +000010739Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000010740 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000010741 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000010742
Owen Anderson7e057142006-07-10 22:03:18 +000010743 if (Value *V = PN.hasConstantValue())
10744 return ReplaceInstUsesWith(PN, V);
10745
Owen Anderson7e057142006-07-10 22:03:18 +000010746 // If all PHI operands are the same operation, pull them through the PHI,
10747 // reducing code size.
10748 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000010749 isa<Instruction>(PN.getIncomingValue(1)) &&
10750 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10751 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10752 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10753 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000010754 PN.getIncomingValue(0)->hasOneUse())
10755 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10756 return Result;
10757
10758 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10759 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10760 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010761 if (PN.hasOneUse()) {
10762 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10763 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000010764 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000010765 PotentiallyDeadPHIs.insert(&PN);
10766 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010767 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000010768 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010769
10770 // If this phi has a single use, and if that use just computes a value for
10771 // the next iteration of a loop, delete the phi. This occurs with unused
10772 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10773 // common case here is good because the only other things that catch this
10774 // are induction variable analysis (sometimes) and ADCE, which is only run
10775 // late.
10776 if (PHIUser->hasOneUse() &&
10777 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10778 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010779 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000010780 }
10781 }
Owen Anderson7e057142006-07-10 22:03:18 +000010782
Chris Lattnercf5008a2007-11-06 21:52:06 +000010783 // We sometimes end up with phi cycles that non-obviously end up being the
10784 // same value, for example:
10785 // z = some value; x = phi (y, z); y = phi (x, z)
10786 // where the phi nodes don't necessarily need to be in the same block. Do a
10787 // quick check to see if the PHI node only contains a single non-phi value, if
10788 // so, scan to see if the phi cycle is actually equal to that value.
10789 {
10790 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10791 // Scan for the first non-phi operand.
10792 while (InValNo != NumOperandVals &&
10793 isa<PHINode>(PN.getIncomingValue(InValNo)))
10794 ++InValNo;
10795
10796 if (InValNo != NumOperandVals) {
10797 Value *NonPhiInVal = PN.getOperand(InValNo);
10798
10799 // Scan the rest of the operands to see if there are any conflicts, if so
10800 // there is no need to recursively scan other phis.
10801 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10802 Value *OpVal = PN.getIncomingValue(InValNo);
10803 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10804 break;
10805 }
10806
10807 // If we scanned over all operands, then we have one unique value plus
10808 // phi values. Scan PHI nodes to see if they all merge in each other or
10809 // the value.
10810 if (InValNo == NumOperandVals) {
10811 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10812 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10813 return ReplaceInstUsesWith(PN, NonPhiInVal);
10814 }
10815 }
10816 }
Chris Lattner60921c92003-12-19 05:58:40 +000010817 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000010818}
10819
Chris Lattner7e708292002-06-25 16:13:24 +000010820Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +000010821 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +000010822 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +000010823 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010824 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +000010825 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010826
Chris Lattnere87597f2004-10-16 18:11:37 +000010827 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010828 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000010829
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010830 bool HasZeroPointerIndex = false;
10831 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10832 HasZeroPointerIndex = C->isNullValue();
10833
10834 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +000010835 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +000010836
Chris Lattner28977af2004-04-05 01:30:19 +000010837 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000010838 if (TD) {
10839 bool MadeChange = false;
10840 unsigned PtrSize = TD->getPointerSizeInBits();
10841
10842 gep_type_iterator GTI = gep_type_begin(GEP);
10843 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10844 I != E; ++I, ++GTI) {
10845 if (!isa<SequentialType>(*GTI)) continue;
10846
Chris Lattnercb69a4e2004-04-07 18:38:20 +000010847 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000010848 // to what we need. If narrower, sign-extend it to what we need. This
10849 // explicit cast can make subsequent optimizations more obvious.
10850 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10851
10852 if (OpBits == PtrSize)
10853 continue;
10854
10855 Instruction::CastOps Opc =
10856 OpBits > PtrSize ? Instruction::Trunc : Instruction::SExt;
10857 *I = InsertCastBefore(Opc, *I, TD->getIntPtrType(GEP.getContext()), GEP);
10858 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000010859 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000010860 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000010861 }
Chris Lattner28977af2004-04-05 01:30:19 +000010862
Chris Lattner90ac28c2002-08-02 19:29:35 +000010863 // Combine Indices - If the source pointer to this getelementptr instruction
10864 // is a getelementptr instruction, combine the indices of the two
10865 // getelementptr instructions into a single instruction.
10866 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010867 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000010868 // Note that if our source is a gep chain itself that we wait for that
10869 // chain to be resolved before we perform this transformation. This
10870 // avoids us creating a TON of code in some cases.
10871 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010872 if (GetElementPtrInst *SrcGEP =
10873 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10874 if (SrcGEP->getNumOperands() == 2)
10875 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000010876
Chris Lattner72588fc2007-02-15 22:48:32 +000010877 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000010878
10879 // Find out whether the last index in the source GEP is a sequential idx.
10880 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000010881 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10882 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000010883 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010884
Chris Lattner90ac28c2002-08-02 19:29:35 +000010885 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000010886 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000010887 // Replace: gep (gep %P, long B), long A, ...
10888 // With: T = long A+B; gep %P, T, ...
10889 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010890 Value *Sum;
10891 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10892 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000010893 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010894 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000010895 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000010896 Sum = SO1;
10897 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000010898 // If they aren't the same type, then the input hasn't been processed
10899 // by the loop above yet (which canonicalizes sequential index types to
10900 // intptr_t). Just avoid transforming this until the input has been
10901 // normalized.
10902 if (SO1->getType() != GO1->getType())
10903 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010904 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000010905 }
Chris Lattner620ce142004-05-07 22:09:22 +000010906
Chris Lattnerab984842009-08-30 05:30:55 +000010907 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010908 if (Src->getNumOperands() == 2) {
10909 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000010910 GEP.setOperand(1, Sum);
10911 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000010912 }
Chris Lattnerab984842009-08-30 05:30:55 +000010913 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000010914 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000010915 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000010916 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000010917 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010918 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000010919 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000010920 Indices.append(Src->op_begin()+1, Src->op_end());
10921 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000010922 }
10923
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010924 if (!Indices.empty()) {
Chris Lattnerccf4b342009-08-30 04:49:01 +000010925 GetElementPtrInst *NewGEP =
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010926 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000010927 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000010928 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010929 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10930 return NewGEP;
10931 }
Chris Lattner6e24d832009-08-30 05:00:50 +000010932 }
10933
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000010934 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10935 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000010936 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10937
10938 if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010939 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10940 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010941 //
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010942 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10943 // into : GEP i8* X, ...
10944 //
Chris Lattnereed48272005-09-13 00:40:14 +000010945 // This occurs when the program declares an array extern like "int X[];"
Chris Lattnereed48272005-09-13 00:40:14 +000010946 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10947 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010948 if (const ArrayType *CATy =
10949 dyn_cast<ArrayType>(CPTy->getElementType())) {
10950 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10951 if (CATy->getElementType() == XTy->getElementType()) {
10952 // -> GEP i8* X, ...
10953 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010954 GetElementPtrInst *NewGEP =
10955 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10956 GEP.getName());
10957 if (cast<GEPOperator>(&GEP)->isInBounds())
10958 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10959 return NewGEP;
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010960 } else if (const ArrayType *XATy =
10961 dyn_cast<ArrayType>(XTy->getElementType())) {
10962 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000010963 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010964 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000010965 // At this point, we know that the cast source type is a pointer
10966 // to an array of the same type as the destination pointer
10967 // array. Because the array type is never stepped over (there
10968 // is a leading zero) we can fold the cast into this GEP.
10969 GEP.setOperand(0, X);
10970 return &GEP;
10971 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000010972 }
10973 }
Chris Lattnereed48272005-09-13 00:40:14 +000010974 } else if (GEP.getNumOperands() == 2) {
10975 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010976 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10977 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000010978 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10979 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010980 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000010981 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10982 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000010983 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000010984 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000010985 Idx[1] = GEP.getOperand(1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010986 Value *NewGEP =
10987 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000010988 if (cast<GEPOperator>(&GEP)->isInBounds())
10989 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000010990 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010991 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000010992 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000010993
10994 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010995 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000010996 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000010997 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000010998
Owen Anderson1d0be152009-08-13 21:58:54 +000010999 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000011000 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000011001 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011002
11003 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11004 // allow either a mul, shift, or constant here.
11005 Value *NewIdx = 0;
11006 ConstantInt *Scale = 0;
11007 if (ArrayEltSize == 1) {
11008 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000011009 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011010 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011011 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011012 Scale = CI;
11013 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11014 if (Inst->getOpcode() == Instruction::Shl &&
11015 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000011016 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11017 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000011018 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000011019 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000011020 NewIdx = Inst->getOperand(0);
11021 } else if (Inst->getOpcode() == Instruction::Mul &&
11022 isa<ConstantInt>(Inst->getOperand(1))) {
11023 Scale = cast<ConstantInt>(Inst->getOperand(1));
11024 NewIdx = Inst->getOperand(0);
11025 }
11026 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011027
Chris Lattner7835cdd2005-09-13 18:36:04 +000011028 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011029 // out, perform the transformation. Note, we don't know whether Scale is
11030 // signed or not. We'll use unsigned version of division/modulo
11031 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000011032 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011033 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000011034 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000011035 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000011036 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000011037 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11038 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011039 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000011040 }
11041
11042 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000011043 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011044 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011045 Idx[1] = NewIdx;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011046 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011047 if (cast<GEPOperator>(&GEP)->isInBounds())
11048 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
Reid Spencer3da59db2006-11-27 01:05:10 +000011049 // The NewGEP must be pointer typed, so must the old one -> BitCast
11050 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000011051 }
11052 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000011053 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000011054 }
Chris Lattner58407792009-01-09 04:53:57 +000011055
Chris Lattner46cd5a12009-01-09 05:44:56 +000011056 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000011057 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000011058 /// Y = gep X, <...constant indices...>
11059 /// into a gep of the original struct. This is important for SROA and alias
11060 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000011061 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011062 if (TD &&
11063 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000011064 // Determine how much the GEP moves the pointer. We are guaranteed to get
11065 // a constant back from EmitGEPOffset.
Owen Andersond672ecb2009-07-03 00:17:18 +000011066 ConstantInt *OffsetV =
11067 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000011068 int64_t Offset = OffsetV->getSExtValue();
11069
11070 // If this GEP instruction doesn't move the pointer, just replace the GEP
11071 // with a bitcast of the real input to the dest type.
11072 if (Offset == 0) {
11073 // If the bitcast is of an allocation, and the allocation will be
11074 // converted to match the type of the cast, don't touch this.
11075 if (isa<AllocationInst>(BCI->getOperand(0))) {
11076 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11077 if (Instruction *I = visitBitCast(*BCI)) {
11078 if (I != BCI) {
11079 I->takeName(BCI);
11080 BCI->getParent()->getInstList().insert(BCI, I);
11081 ReplaceInstUsesWith(*BCI, I);
11082 }
11083 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000011084 }
Chris Lattner58407792009-01-09 04:53:57 +000011085 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011086 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000011087 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000011088
11089 // Otherwise, if the offset is non-zero, we need to find out if there is a
11090 // field at Offset in 'A's type. If so, we can pull the cast through the
11091 // GEP.
11092 SmallVector<Value*, 8> NewIndices;
11093 const Type *InTy =
11094 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000011095 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011096 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11097 NewIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011098 if (cast<GEPOperator>(&GEP)->isInBounds())
11099 cast<GEPOperator>(NGEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011100
11101 if (NGEP->getType() == GEP.getType())
11102 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000011103 NGEP->takeName(&GEP);
11104 return new BitCastInst(NGEP, GEP.getType());
11105 }
Chris Lattner58407792009-01-09 04:53:57 +000011106 }
11107 }
11108
Chris Lattner8a2a3112001-12-14 16:52:21 +000011109 return 0;
11110}
11111
Chris Lattner0864acf2002-11-04 16:18:53 +000011112Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11113 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011114 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000011115 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11116 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000011117 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +000011118 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +000011119
11120 // Create and insert the replacement instruction...
11121 if (isa<MallocInst>(AI))
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011122 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011123 else {
11124 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011125 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +000011126 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011127 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000011128
Chris Lattner0864acf2002-11-04 16:18:53 +000011129 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000011130 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000011131 //
11132 BasicBlock::iterator It = New;
Dale Johannesena8915182009-03-11 22:19:43 +000011133 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000011134
11135 // Now that I is pointing to the first non-allocation-inst in the block,
11136 // insert our getelementptr instruction...
11137 //
Owen Anderson1d0be152009-08-13 21:58:54 +000011138 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000011139 Value *Idx[2];
11140 Idx[0] = NullIdx;
11141 Idx[1] = NullIdx;
Gabor Greif051a9502008-04-06 20:25:17 +000011142 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11143 New->getName()+".sub", It);
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011144 cast<GEPOperator>(V)->setIsInBounds(true);
Chris Lattner0864acf2002-11-04 16:18:53 +000011145
11146 // Now make everything use the getelementptr instead of the original
11147 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000011148 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000011149 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000011150 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000011151 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011152 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011153
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011154 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000011155 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000011156 // Note that we only do this for alloca's, because malloc should allocate
11157 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000011158 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000011159 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000011160
11161 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11162 if (AI.getAlignment() == 0)
11163 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11164 }
Chris Lattner7c881df2004-03-19 06:08:10 +000011165
Chris Lattner0864acf2002-11-04 16:18:53 +000011166 return 0;
11167}
11168
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011169Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11170 Value *Op = FI.getOperand(0);
11171
Chris Lattner17be6352004-10-18 02:59:09 +000011172 // free undef -> unreachable.
11173 if (isa<UndefValue>(Op)) {
11174 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000011175 new StoreInst(ConstantInt::getTrue(*Context),
Owen Anderson1d0be152009-08-13 21:58:54 +000011176 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +000011177 return EraseInstFromFunction(FI);
11178 }
Chris Lattner6fe55412007-04-14 00:20:02 +000011179
Chris Lattner6160e852004-02-28 04:57:37 +000011180 // If we have 'free null' delete the instruction. This can happen in stl code
11181 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +000011182 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +000011183 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011184
11185 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11186 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11187 FI.setOperand(0, CI->getOperand(0));
11188 return &FI;
11189 }
11190
11191 // Change free (gep X, 0,0,0,0) into free(X)
11192 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11193 if (GEPI->hasAllZeroIndices()) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000011194 Worklist.Add(GEPI);
Chris Lattner6fe55412007-04-14 00:20:02 +000011195 FI.setOperand(0, GEPI->getOperand(0));
11196 return &FI;
11197 }
11198 }
11199
11200 // Change free(malloc) into nothing, if the malloc has a single use.
11201 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11202 if (MI->hasOneUse()) {
11203 EraseInstFromFunction(FI);
11204 return EraseInstFromFunction(*MI);
11205 }
Chris Lattner6160e852004-02-28 04:57:37 +000011206
Chris Lattner67b1e1b2003-12-07 01:24:23 +000011207 return 0;
11208}
11209
11210
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011211/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000011212static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000011213 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000011214 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000011215 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000011216 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000011217
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011218 if (TD) {
11219 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11220 // Instead of loading constant c string, use corresponding integer value
11221 // directly if string length is small enough.
11222 std::string Str;
11223 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11224 unsigned len = Str.length();
11225 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11226 unsigned numBits = Ty->getPrimitiveSizeInBits();
11227 // Replace LI with immediate integer store.
11228 if ((numBits >> 3) == len + 1) {
11229 APInt StrVal(numBits, 0);
11230 APInt SingleChar(numBits, 0);
11231 if (TD->isLittleEndian()) {
11232 for (signed i = len-1; i >= 0; i--) {
11233 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11234 StrVal = (StrVal << 8) | SingleChar;
11235 }
11236 } else {
11237 for (unsigned i = 0; i < len; i++) {
11238 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11239 StrVal = (StrVal << 8) | SingleChar;
11240 }
11241 // Append NULL at the end.
11242 SingleChar = 0;
Bill Wendling587c01d2008-02-26 10:53:30 +000011243 StrVal = (StrVal << 8) | SingleChar;
11244 }
Owen Andersoneed707b2009-07-24 23:12:02 +000011245 Value *NL = ConstantInt::get(*Context, StrVal);
Nick Lewycky48f95ad2009-05-08 06:47:37 +000011246 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling587c01d2008-02-26 10:53:30 +000011247 }
Devang Patel99db6ad2007-10-18 19:52:32 +000011248 }
11249 }
11250 }
11251
Mon P Wang6753f952009-02-07 22:19:29 +000011252 const PointerType *DestTy = cast<PointerType>(CI->getType());
11253 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011254 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000011255
11256 // If the address spaces don't match, don't eliminate the cast.
11257 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11258 return 0;
11259
Chris Lattnerb89e0712004-07-13 01:49:43 +000011260 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000011261
Reid Spencer42230162007-01-22 05:51:25 +000011262 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011263 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000011264 // If the source is an array, the code below will not succeed. Check to
11265 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11266 // constants.
11267 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11268 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11269 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000011270 Value *Idxs[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000011271 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
Owen Andersonbaf3c402009-07-29 18:55:55 +000011272 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000011273 SrcTy = cast<PointerType>(CastOp->getType());
11274 SrcPTy = SrcTy->getElementType();
11275 }
11276
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011277 if (IC.getTargetData() &&
11278 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000011279 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000011280 // Do not allow turning this into a load of an integer, which is then
11281 // casted to a pointer, this pessimizes pointer analysis a lot.
11282 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011283 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11284 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000011285
Chris Lattnerf9527852005-01-31 04:50:46 +000011286 // Okay, we are casting from one integer or pointer type to another of
11287 // the same size. Instead of casting the pointer before the load, cast
11288 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011289 Value *NewLoad =
11290 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000011291 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000011292 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000011293 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000011294 }
11295 }
11296 return 0;
11297}
11298
Chris Lattner833b8a42003-06-26 05:06:25 +000011299Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11300 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000011301
Dan Gohman9941f742007-07-20 16:34:21 +000011302 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011303 if (TD) {
11304 unsigned KnownAlign =
11305 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11306 if (KnownAlign >
11307 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11308 LI.getAlignment()))
11309 LI.setAlignment(KnownAlign);
11310 }
Dan Gohman9941f742007-07-20 16:34:21 +000011311
Chris Lattner37366c12005-05-01 04:24:53 +000011312 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +000011313 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000011314 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000011315 return Res;
11316
11317 // None of the following transforms are legal for volatile loads.
11318 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000011319
Dan Gohman2276a7b2008-10-15 23:19:35 +000011320 // Do really simple store-to-load forwarding and load CSE, to catch cases
11321 // where there are several consequtive memory accesses to the same location,
11322 // separated by a few arithmetic operations.
11323 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000011324 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11325 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000011326
Christopher Lambb15147e2007-12-29 07:56:53 +000011327 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11328 const Value *GEPI0 = GEPI->getOperand(0);
11329 // TODO: Consider a target hook for valid address spaces for this xform.
11330 if (isa<ConstantPointerNull>(GEPI0) &&
11331 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +000011332 // 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 }
Christopher Lambb15147e2007-12-29 07:56:53 +000011340 }
Chris Lattner37366c12005-05-01 04:24:53 +000011341
Chris Lattnere87597f2004-10-16 18:11:37 +000011342 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +000011343 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +000011344 // TODO: Consider a target hook for valid address spaces for this xform.
11345 if (isa<UndefValue>(C) || (C->isNullValue() &&
11346 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +000011347 // Insert a new store to null instruction before the load to indicate that
11348 // this code is not reachable. We do this instead of inserting an
11349 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011350 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011351 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011352 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000011353 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011354
Chris Lattnere87597f2004-10-16 18:11:37 +000011355 // Instcombine load (constant global) into the value loaded.
11356 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands64da9402009-03-21 21:27:31 +000011357 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattnere87597f2004-10-16 18:11:37 +000011358 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +000011359
Chris Lattnere87597f2004-10-16 18:11:37 +000011360 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011361 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +000011362 if (CE->getOpcode() == Instruction::GetElementPtr) {
11363 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands64da9402009-03-21 21:27:31 +000011364 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Chris Lattner363f2a22005-09-26 05:28:06 +000011365 if (Constant *V =
Owen Anderson50895512009-07-06 18:42:36 +000011366 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
Owen Andersone922c022009-07-22 00:24:57 +000011367 *Context))
Chris Lattnere87597f2004-10-16 18:11:37 +000011368 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +000011369 if (CE->getOperand(0)->isNullValue()) {
11370 // Insert a new store to null instruction before the load to indicate
11371 // that this code is not reachable. We do this instead of inserting
11372 // an unreachable instruction directly because we cannot modify the
11373 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011374 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000011375 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011376 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000011377 }
11378
Reid Spencer3da59db2006-11-27 01:05:10 +000011379 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +000011380 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +000011381 return Res;
11382 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000011383 }
Chris Lattnere87597f2004-10-16 18:11:37 +000011384 }
Chris Lattner8d2e8882007-08-11 18:48:48 +000011385
11386 // If this load comes from anywhere in a constant global, and if the global
11387 // is all undef or zero, we know what it loads.
Duncan Sands5d0392c2008-10-01 15:25:41 +000011388 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands64da9402009-03-21 21:27:31 +000011389 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner8d2e8882007-08-11 18:48:48 +000011390 if (GV->getInitializer()->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +000011391 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011392 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011393 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner8d2e8882007-08-11 18:48:48 +000011394 }
11395 }
Chris Lattnerf499eac2004-04-08 20:39:49 +000011396
Chris Lattner37366c12005-05-01 04:24:53 +000011397 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000011398 // Change select and PHI nodes to select values instead of addresses: this
11399 // helps alias analysis out a lot, allows many others simplifications, and
11400 // exposes redundancy in the code.
11401 //
11402 // Note that we cannot do the transformation unless we know that the
11403 // introduced loads cannot trap! Something like this is valid as long as
11404 // the condition is always false: load (select bool %C, int* null, int* %G),
11405 // but it would not be valid if we transformed it to load from null
11406 // unconditionally.
11407 //
11408 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11409 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000011410 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11411 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011412 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11413 SI->getOperand(1)->getName()+".val");
11414 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11415 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000011416 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000011417 }
11418
Chris Lattner684fe212004-09-23 15:46:00 +000011419 // load (select (cond, null, P)) -> load P
11420 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11421 if (C->isNullValue()) {
11422 LI.setOperand(0, SI->getOperand(2));
11423 return &LI;
11424 }
11425
11426 // load (select (cond, P, null)) -> load P
11427 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11428 if (C->isNullValue()) {
11429 LI.setOperand(0, SI->getOperand(1));
11430 return &LI;
11431 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000011432 }
11433 }
Chris Lattner833b8a42003-06-26 05:06:25 +000011434 return 0;
11435}
11436
Reid Spencer55af2b52007-01-19 21:20:31 +000011437/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000011438/// when possible. This makes it generally easy to do alias analysis and/or
11439/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011440static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11441 User *CI = cast<User>(SI.getOperand(1));
11442 Value *CastOp = CI->getOperand(0);
11443
11444 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011445 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11446 if (SrcTy == 0) return 0;
11447
11448 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011449
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011450 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11451 return 0;
11452
Chris Lattner3914f722009-01-24 01:00:13 +000011453 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11454 /// to its first element. This allows us to handle things like:
11455 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11456 /// on 32-bit hosts.
11457 SmallVector<Value*, 4> NewGEPIndices;
11458
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011459 // If the source is an array, the code below will not succeed. Check to
11460 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11461 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000011462 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11463 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000011464 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000011465 NewGEPIndices.push_back(Zero);
11466
11467 while (1) {
11468 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000011469 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000011470 break;
Chris Lattner3914f722009-01-24 01:00:13 +000011471 NewGEPIndices.push_back(Zero);
11472 SrcPTy = STy->getElementType(0);
11473 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11474 NewGEPIndices.push_back(Zero);
11475 SrcPTy = ATy->getElementType();
11476 } else {
11477 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011478 }
Chris Lattner3914f722009-01-24 01:00:13 +000011479 }
11480
Owen Andersondebcb012009-07-29 22:17:13 +000011481 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000011482 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011483
11484 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11485 return 0;
11486
Chris Lattner71759c42009-01-16 20:12:52 +000011487 // If the pointers point into different address spaces or if they point to
11488 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011489 if (!IC.getTargetData() ||
11490 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000011491 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011492 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11493 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011494 return 0;
11495
11496 // Okay, we are casting from one integer or pointer type to another of
11497 // the same size. Instead of casting the pointer before
11498 // the store, cast the value to be stored.
11499 Value *NewCast;
11500 Value *SIOp0 = SI.getOperand(0);
11501 Instruction::CastOps opcode = Instruction::BitCast;
11502 const Type* CastSrcTy = SIOp0->getType();
11503 const Type* CastDstTy = SrcPTy;
11504 if (isa<PointerType>(CastDstTy)) {
11505 if (CastSrcTy->isInteger())
11506 opcode = Instruction::IntToPtr;
11507 } else if (isa<IntegerType>(CastDstTy)) {
11508 if (isa<PointerType>(SIOp0->getType()))
11509 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011510 }
Chris Lattner3914f722009-01-24 01:00:13 +000011511
11512 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11513 // emit a GEP to index into its first field.
11514 if (!NewGEPIndices.empty()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011515 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11516 NewGEPIndices.end());
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011517 cast<GEPOperator>(CastOp)->setIsInBounds(true);
Chris Lattner3914f722009-01-24 01:00:13 +000011518 }
11519
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011520 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11521 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000011522 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011523}
11524
Chris Lattner4aebaee2008-11-27 08:56:30 +000011525/// equivalentAddressValues - Test if A and B will obviously have the same
11526/// value. This includes recognizing that %t0 and %t1 will have the same
11527/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011528/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011529/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000011530/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000011531/// %t2 = load i32* %t1
11532///
11533static bool equivalentAddressValues(Value *A, Value *B) {
11534 // Test if the values are trivially equivalent.
11535 if (A == B) return true;
11536
11537 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011538 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11539 // its only used to compare two uses within the same basic block, which
11540 // means that they'll always either have the same value or one of them
11541 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000011542 if (isa<BinaryOperator>(A) ||
11543 isa<CastInst>(A) ||
11544 isa<PHINode>(A) ||
11545 isa<GetElementPtrInst>(A))
11546 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000011547 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000011548 return true;
11549
11550 // Otherwise they may not be equivalent.
11551 return false;
11552}
11553
Dale Johannesen4945c652009-03-03 21:26:39 +000011554// If this instruction has two uses, one of which is a llvm.dbg.declare,
11555// return the llvm.dbg.declare.
11556DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11557 if (!V->hasNUses(2))
11558 return 0;
11559 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11560 UI != E; ++UI) {
11561 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11562 return DI;
11563 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11564 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11565 return DI;
11566 }
11567 }
11568 return 0;
11569}
11570
Chris Lattner2f503e62005-01-31 05:36:43 +000011571Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11572 Value *Val = SI.getOperand(0);
11573 Value *Ptr = SI.getOperand(1);
11574
11575 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +000011576 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011577 ++NumCombined;
11578 return 0;
11579 }
Chris Lattner836692d2007-01-15 06:51:56 +000011580
11581 // If the RHS is an alloca with a single use, zapify the store, making the
11582 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000011583 // If the RHS is an alloca with a two uses, the other one being a
11584 // llvm.dbg.declare, zapify the store and the declare, making the
11585 // alloca dead. We must do this to prevent declare's from affecting
11586 // codegen.
11587 if (!SI.isVolatile()) {
11588 if (Ptr->hasOneUse()) {
11589 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000011590 EraseInstFromFunction(SI);
11591 ++NumCombined;
11592 return 0;
11593 }
Dale Johannesen4945c652009-03-03 21:26:39 +000011594 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11595 if (isa<AllocaInst>(GEP->getOperand(0))) {
11596 if (GEP->getOperand(0)->hasOneUse()) {
11597 EraseInstFromFunction(SI);
11598 ++NumCombined;
11599 return 0;
11600 }
11601 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11602 EraseInstFromFunction(*DI);
11603 EraseInstFromFunction(SI);
11604 ++NumCombined;
11605 return 0;
11606 }
11607 }
11608 }
11609 }
11610 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11611 EraseInstFromFunction(*DI);
11612 EraseInstFromFunction(SI);
11613 ++NumCombined;
11614 return 0;
11615 }
Chris Lattner836692d2007-01-15 06:51:56 +000011616 }
Chris Lattner2f503e62005-01-31 05:36:43 +000011617
Dan Gohman9941f742007-07-20 16:34:21 +000011618 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000011619 if (TD) {
11620 unsigned KnownAlign =
11621 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11622 if (KnownAlign >
11623 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11624 SI.getAlignment()))
11625 SI.setAlignment(KnownAlign);
11626 }
Dan Gohman9941f742007-07-20 16:34:21 +000011627
Dale Johannesenacb51a32009-03-03 01:43:03 +000011628 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000011629 // stores to the same location, separated by a few arithmetic operations. This
11630 // situation often occurs with bitfield accesses.
11631 BasicBlock::iterator BBI = &SI;
11632 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11633 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000011634 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011635 // Don't count debug info directives, lest they affect codegen,
11636 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11637 // It is necessary for correctness to skip those that feed into a
11638 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000011639 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000011640 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000011641 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000011642 continue;
11643 }
Chris Lattner9ca96412006-02-08 03:25:32 +000011644
11645 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11646 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000011647 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11648 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011649 ++NumDeadStore;
11650 ++BBI;
11651 EraseInstFromFunction(*PrevSI);
11652 continue;
11653 }
11654 break;
11655 }
11656
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011657 // If this is a load, we have to stop. However, if the loaded value is from
11658 // the pointer we're loading and is producing the pointer we're storing,
11659 // then *this* store is dead (X = load P; store X -> P).
11660 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000011661 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11662 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000011663 EraseInstFromFunction(SI);
11664 ++NumCombined;
11665 return 0;
11666 }
11667 // Otherwise, this is a load from some other location. Stores before it
11668 // may not be dead.
11669 break;
11670 }
11671
Chris Lattner9ca96412006-02-08 03:25:32 +000011672 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000011673 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000011674 break;
11675 }
11676
11677
11678 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000011679
11680 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner3590abf2009-06-11 17:54:56 +000011681 if (isa<ConstantPointerNull>(Ptr) &&
11682 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000011683 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011684 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000011685 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000011686 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000011687 ++NumCombined;
11688 }
11689 return 0; // Do not modify these!
11690 }
11691
11692 // store undef, Ptr -> noop
11693 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000011694 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000011695 ++NumCombined;
11696 return 0;
11697 }
11698
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011699 // If the pointer destination is a cast, see if we can fold the cast into the
11700 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000011701 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011702 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11703 return Res;
11704 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000011705 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000011706 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11707 return Res;
11708
Chris Lattner408902b2005-09-12 23:23:25 +000011709
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011710 // If this store is the last instruction in the basic block (possibly
11711 // excepting debug info instructions and the pointer bitcasts that feed
11712 // into them), and if the block ends with an unconditional branch, try
11713 // to move it to the successor block.
11714 BBI = &SI;
11715 do {
11716 ++BBI;
11717 } while (isa<DbgInfoIntrinsic>(BBI) ||
11718 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000011719 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011720 if (BI->isUnconditional())
11721 if (SimplifyStoreAtEndOfBlock(SI))
11722 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000011723
Chris Lattner2f503e62005-01-31 05:36:43 +000011724 return 0;
11725}
11726
Chris Lattner3284d1f2007-04-15 00:07:55 +000011727/// SimplifyStoreAtEndOfBlock - Turn things like:
11728/// if () { *P = v1; } else { *P = v2 }
11729/// into a phi node with a store in the successor.
11730///
Chris Lattner31755a02007-04-15 01:02:18 +000011731/// Simplify things like:
11732/// *P = v1; if () { *P = v2; }
11733/// into a phi node with a store in the successor.
11734///
Chris Lattner3284d1f2007-04-15 00:07:55 +000011735bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11736 BasicBlock *StoreBB = SI.getParent();
11737
11738 // Check to see if the successor block has exactly two incoming edges. If
11739 // so, see if the other predecessor contains a store to the same location.
11740 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000011741 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000011742
11743 // Determine whether Dest has exactly two predecessors and, if so, compute
11744 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000011745 pred_iterator PI = pred_begin(DestBB);
11746 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011747 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000011748 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011749 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000011750 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011751 return false;
11752
11753 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000011754 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000011755 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000011756 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000011757 }
Chris Lattner31755a02007-04-15 01:02:18 +000011758 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000011759 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000011760
11761 // Bail out if all the relevant blocks aren't distinct (this can happen,
11762 // for example, if SI is in an infinite loop)
11763 if (StoreBB == DestBB || OtherBB == DestBB)
11764 return false;
11765
Chris Lattner31755a02007-04-15 01:02:18 +000011766 // Verify that the other block ends in a branch and is not otherwise empty.
11767 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011768 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000011769 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000011770 return false;
11771
Chris Lattner31755a02007-04-15 01:02:18 +000011772 // If the other block ends in an unconditional branch, check for the 'if then
11773 // else' case. there is an instruction before the branch.
11774 StoreInst *OtherStore = 0;
11775 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000011776 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000011777 // Skip over debugging info.
11778 while (isa<DbgInfoIntrinsic>(BBI) ||
11779 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11780 if (BBI==OtherBB->begin())
11781 return false;
11782 --BBI;
11783 }
11784 // If this isn't a store, or isn't a store to the same location, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000011785 OtherStore = dyn_cast<StoreInst>(BBI);
11786 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11787 return false;
11788 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000011789 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000011790 // destinations is StoreBB, then we have the if/then case.
11791 if (OtherBr->getSuccessor(0) != StoreBB &&
11792 OtherBr->getSuccessor(1) != StoreBB)
11793 return false;
11794
11795 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000011796 // if/then triangle. See if there is a store to the same ptr as SI that
11797 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011798 for (;; --BBI) {
11799 // Check to see if we find the matching store.
11800 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11801 if (OtherStore->getOperand(1) != SI.getOperand(1))
11802 return false;
11803 break;
11804 }
Eli Friedman6903a242008-06-13 22:02:12 +000011805 // If we find something that may be using or overwriting the stored
11806 // value, or if we run out of instructions, we can't do the xform.
11807 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000011808 BBI == OtherBB->begin())
11809 return false;
11810 }
11811
11812 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000011813 // make sure nothing reads or overwrites the stored value in
11814 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000011815 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11816 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000011817 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000011818 return false;
11819 }
11820 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000011821
Chris Lattner31755a02007-04-15 01:02:18 +000011822 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000011823 Value *MergedVal = OtherStore->getOperand(0);
11824 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011825 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000011826 PN->reserveOperandSpace(2);
11827 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000011828 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11829 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000011830 }
11831
11832 // Advance to a place where it is safe to insert the new store and
11833 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000011834 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000011835 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11836 OtherStore->isVolatile()), *BBI);
11837
11838 // Nuke the old stores.
11839 EraseInstFromFunction(SI);
11840 EraseInstFromFunction(*OtherStore);
11841 ++NumCombined;
11842 return true;
11843}
11844
Chris Lattner2f503e62005-01-31 05:36:43 +000011845
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011846Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11847 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000011848 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011849 BasicBlock *TrueDest;
11850 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000011851 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000011852 !isa<Constant>(X)) {
11853 // Swap Destinations and condition...
11854 BI.setCondition(X);
11855 BI.setSuccessor(0, FalseDest);
11856 BI.setSuccessor(1, TrueDest);
11857 return &BI;
11858 }
11859
Reid Spencere4d87aa2006-12-23 06:05:41 +000011860 // Cannonicalize fcmp_one -> fcmp_oeq
11861 FCmpInst::Predicate FPred; Value *Y;
11862 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011863 TrueDest, FalseDest)) &&
11864 BI.getCondition()->hasOneUse())
11865 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11866 FPred == FCmpInst::FCMP_OGE) {
11867 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11868 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11869
11870 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000011871 BI.setSuccessor(0, FalseDest);
11872 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011873 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000011874 return &BI;
11875 }
11876
11877 // Cannonicalize icmp_ne -> icmp_eq
11878 ICmpInst::Predicate IPred;
11879 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000011880 TrueDest, FalseDest)) &&
11881 BI.getCondition()->hasOneUse())
11882 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11883 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11884 IPred == ICmpInst::ICMP_SGE) {
11885 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11886 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11887 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000011888 BI.setSuccessor(0, FalseDest);
11889 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000011890 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000011891 return &BI;
11892 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011893
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000011894 return 0;
11895}
Chris Lattner0864acf2002-11-04 16:18:53 +000011896
Chris Lattner46238a62004-07-03 00:26:11 +000011897Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11898 Value *Cond = SI.getCondition();
11899 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11900 if (I->getOpcode() == Instruction::Add)
11901 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11902 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11903 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000011904 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000011905 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000011906 AddRHS));
11907 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000011908 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000011909 return &SI;
11910 }
11911 }
11912 return 0;
11913}
11914
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011915Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011916 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011917
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011918 if (!EV.hasIndices())
11919 return ReplaceInstUsesWith(EV, Agg);
11920
11921 if (Constant *C = dyn_cast<Constant>(Agg)) {
11922 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011923 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011924
11925 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000011926 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011927
11928 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11929 // Extract the element indexed by the first index out of the constant
11930 Value *V = C->getOperand(*EV.idx_begin());
11931 if (EV.getNumIndices() > 1)
11932 // Extract the remaining indices out of the constant indexed by the
11933 // first index
11934 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11935 else
11936 return ReplaceInstUsesWith(EV, V);
11937 }
11938 return 0; // Can't handle other constants
11939 }
11940 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11941 // We're extracting from an insertvalue instruction, compare the indices
11942 const unsigned *exti, *exte, *insi, *inse;
11943 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11944 exte = EV.idx_end(), inse = IV->idx_end();
11945 exti != exte && insi != inse;
11946 ++exti, ++insi) {
11947 if (*insi != *exti)
11948 // The insert and extract both reference distinctly different elements.
11949 // This means the extract is not influenced by the insert, and we can
11950 // replace the aggregate operand of the extract with the aggregate
11951 // operand of the insert. i.e., replace
11952 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11953 // %E = extractvalue { i32, { i32 } } %I, 0
11954 // with
11955 // %E = extractvalue { i32, { i32 } } %A, 0
11956 return ExtractValueInst::Create(IV->getAggregateOperand(),
11957 EV.idx_begin(), EV.idx_end());
11958 }
11959 if (exti == exte && insi == inse)
11960 // Both iterators are at the end: Index lists are identical. Replace
11961 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11962 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11963 // with "i32 42"
11964 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11965 if (exti == exte) {
11966 // The extract list is a prefix of the insert list. i.e. replace
11967 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11968 // %E = extractvalue { i32, { i32 } } %I, 1
11969 // with
11970 // %X = extractvalue { i32, { i32 } } %A, 1
11971 // %E = insertvalue { i32 } %X, i32 42, 0
11972 // by switching the order of the insert and extract (though the
11973 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000011974 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11975 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000011976 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11977 insi, inse);
11978 }
11979 if (insi == inse)
11980 // The insert list is a prefix of the extract list
11981 // We can simply remove the common indices from the extract and make it
11982 // operate on the inserted value instead of the insertvalue result.
11983 // i.e., replace
11984 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11985 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11986 // with
11987 // %E extractvalue { i32 } { i32 42 }, 0
11988 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11989 exti, exte);
11990 }
11991 // Can't simplify extracts from other values. Note that nested extracts are
11992 // already simplified implicitely by the above (extract ( extract (insert) )
11993 // will be translated into extract ( insert ( extract ) ) first and then just
11994 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000011995 return 0;
11996}
11997
Chris Lattner220b0cf2006-03-05 00:22:33 +000011998/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11999/// is to leave as a vector operation.
12000static bool CheapToScalarize(Value *V, bool isConstant) {
12001 if (isa<ConstantAggregateZero>(V))
12002 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012003 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012004 if (isConstant) return true;
12005 // If all elts are the same, we can extract.
12006 Constant *Op0 = C->getOperand(0);
12007 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12008 if (C->getOperand(i) != Op0)
12009 return false;
12010 return true;
12011 }
12012 Instruction *I = dyn_cast<Instruction>(V);
12013 if (!I) return false;
12014
12015 // Insert element gets simplified to the inserted element or is deleted if
12016 // this is constant idx extract element and its a constant idx insertelt.
12017 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12018 isa<ConstantInt>(I->getOperand(2)))
12019 return true;
12020 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12021 return true;
12022 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12023 if (BO->hasOneUse() &&
12024 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12025 CheapToScalarize(BO->getOperand(1), isConstant)))
12026 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000012027 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12028 if (CI->hasOneUse() &&
12029 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12030 CheapToScalarize(CI->getOperand(1), isConstant)))
12031 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000012032
12033 return false;
12034}
12035
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000012036/// Read and decode a shufflevector mask.
12037///
12038/// It turns undef elements into values that are larger than the number of
12039/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000012040static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12041 unsigned NElts = SVI->getType()->getNumElements();
12042 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12043 return std::vector<unsigned>(NElts, 0);
12044 if (isa<UndefValue>(SVI->getOperand(2)))
12045 return std::vector<unsigned>(NElts, 2*NElts);
12046
12047 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000012048 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000012049 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12050 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000012051 Result.push_back(NElts*2); // undef -> 8
12052 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000012053 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000012054 return Result;
12055}
12056
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012057/// FindScalarElement - Given a vector and an element number, see if the scalar
12058/// value is already around as a register, for example if it were inserted then
12059/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000012060static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012061 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012062 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12063 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000012064 unsigned Width = PTy->getNumElements();
12065 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012066 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012067
12068 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012069 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012070 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000012071 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000012072 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012073 return CP->getOperand(EltNo);
12074 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12075 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000012076 if (!isa<ConstantInt>(III->getOperand(2)))
12077 return 0;
12078 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012079
12080 // If this is an insert to the element we are looking for, return the
12081 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000012082 if (EltNo == IIElt)
12083 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012084
12085 // Otherwise, the insertelement doesn't modify the value, recurse on its
12086 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000012087 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000012088 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000012089 unsigned LHSWidth =
12090 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000012091 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000012092 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012093 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012094 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000012095 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000012096 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012097 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012098 }
12099
12100 // Otherwise, we don't know.
12101 return 0;
12102}
12103
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012104Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000012105 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000012106 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012107 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012108
Dan Gohman07a96762007-07-16 14:29:03 +000012109 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000012110 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000012111 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000012112
Reid Spencer9d6565a2007-02-15 02:26:10 +000012113 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000012114 // If vector val is constant with all elements the same, replace EI with
12115 // that element. When the elements are not identical, we cannot replace yet
12116 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000012117 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012118 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000012119 if (C->getOperand(i) != op0) {
12120 op0 = 0;
12121 break;
12122 }
12123 if (op0)
12124 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012125 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000012126
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012127 // If extracting a specified index from the vector, see if we can recursively
12128 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000012129 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000012130 unsigned IndexVal = IdxC->getZExtValue();
Eli Friedman76e7ba82009-07-18 19:04:16 +000012131 unsigned VectorWidth =
12132 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000012133
12134 // If this is extracting an invalid index, turn this into undef, to avoid
12135 // crashing the code below.
12136 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012137 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000012138
Chris Lattner867b99f2006-10-05 06:55:50 +000012139 // This instruction only demands the single element from the input vector.
12140 // If the input vector has a single use, simplify it based on this use
12141 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000012142 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000012143 APInt UndefElts(VectorWidth, 0);
12144 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000012145 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000012146 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000012147 EI.setOperand(0, V);
12148 return &EI;
12149 }
12150 }
12151
Owen Andersond672ecb2009-07-03 00:17:18 +000012152 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012153 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012154
12155 // If the this extractelement is directly using a bitcast from a vector of
12156 // the same number of elements, see if we can find the source element from
12157 // it. In this case, we will end up needing to bitcast the scalars.
12158 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12159 if (const VectorType *VT =
12160 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12161 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000012162 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12163 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000012164 return new BitCastInst(Elt, EI.getType());
12165 }
Chris Lattner389a6f52006-04-10 23:06:36 +000012166 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000012167
Chris Lattner73fa49d2006-05-25 22:53:38 +000012168 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012169 if (I->hasOneUse()) {
12170 // Push extractelement into predecessor operation if legal and
12171 // profitable to do so
12172 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000012173 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12174 if (CheapToScalarize(BO, isConstantElt)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012175 Value *newEI0 =
12176 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12177 EI.getName()+".lhs");
12178 Value *newEI1 =
12179 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12180 EI.getName()+".rhs");
Gabor Greif7cbd8a32008-05-16 19:29:10 +000012181 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner220b0cf2006-03-05 00:22:33 +000012182 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000012183 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000012184 unsigned AS =
12185 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000012186 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Mon P Wang7c4efa62009-08-13 05:12:13 +000012187 PointerType::get(EI.getType(), AS),*I);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012188 Value *GEP =
12189 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012190 cast<GEPOperator>(GEP)->setIsInBounds(true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012191
12192 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12193
12194 // Make sure the Load goes before the load instruction in the source,
12195 // not wherever the extract happens to be.
12196 Load->moveBefore(I);
12197
Mon P Wang7c4efa62009-08-13 05:12:13 +000012198 return ReplaceInstUsesWith(EI, Load);
Chris Lattner73fa49d2006-05-25 22:53:38 +000012199 }
12200 }
12201 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12202 // Extracting the inserted element?
12203 if (IE->getOperand(2) == EI.getOperand(1))
12204 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12205 // If the inserted and extracted elements are constants, they must not
12206 // be the same value, extract from the pre-inserted value instead.
12207 if (isa<Constant>(IE->getOperand(2)) &&
12208 isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000012209 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000012210 EI.setOperand(0, IE->getOperand(0));
12211 return &EI;
12212 }
12213 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12214 // If this is extracting an element from a shufflevector, figure out where
12215 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000012216 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12217 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000012218 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012219 unsigned LHSWidth =
12220 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12221
12222 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000012223 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000012224 else if (SrcIdx < LHSWidth*2) {
12225 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000012226 Src = SVI->getOperand(1);
12227 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012228 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000012229 }
Eric Christophera3500da2009-07-25 02:28:41 +000012230 return ExtractElementInst::Create(Src,
Owen Anderson1d0be152009-08-13 21:58:54 +000012231 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012232 }
12233 }
Eli Friedman2451a642009-07-18 23:06:53 +000012234 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000012235 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012236 return 0;
12237}
12238
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012239/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12240/// elements from either LHS or RHS, return the shuffle mask and true.
12241/// Otherwise, return false.
12242static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000012243 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012244 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012245 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12246 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012247 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012248
12249 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012250 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012251 return true;
12252 } else if (V == LHS) {
12253 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012254 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012255 return true;
12256 } else if (V == RHS) {
12257 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012258 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012259 return true;
12260 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12261 // If this is an insert of an extract from some other vector, include it.
12262 Value *VecOp = IEI->getOperand(0);
12263 Value *ScalarOp = IEI->getOperand(1);
12264 Value *IdxOp = IEI->getOperand(2);
12265
Chris Lattnerd929f062006-04-27 21:14:21 +000012266 if (!isa<ConstantInt>(IdxOp))
12267 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000012268 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000012269
12270 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12271 // Okay, we can handle this if the vector we are insertinting into is
12272 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012273 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000012274 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012275 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000012276 return true;
12277 }
12278 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12279 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012280 EI->getOperand(0)->getType() == V->getType()) {
12281 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012282 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012283
12284 // This must be extracting from either LHS or RHS.
12285 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12286 // Okay, we can handle this if the vector we are insertinting into is
12287 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000012288 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012289 // If so, update the mask to reflect the inserted value.
12290 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012291 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012292 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012293 } else {
12294 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012295 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012296 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012297
12298 }
12299 return true;
12300 }
12301 }
12302 }
12303 }
12304 }
12305 // TODO: Handle shufflevector here!
12306
12307 return false;
12308}
12309
12310/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12311/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12312/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000012313static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000012314 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000012315 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012316 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000012317 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000012318 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000012319
12320 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012321 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012322 return V;
12323 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012324 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000012325 return V;
12326 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12327 // If this is an insert of an extract from some other vector, include it.
12328 Value *VecOp = IEI->getOperand(0);
12329 Value *ScalarOp = IEI->getOperand(1);
12330 Value *IdxOp = IEI->getOperand(2);
12331
12332 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12333 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12334 EI->getOperand(0)->getType() == V->getType()) {
12335 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000012336 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12337 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012338
12339 // Either the extracted from or inserted into vector must be RHSVec,
12340 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012341 if (EI->getOperand(0) == RHS || RHS == 0) {
12342 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000012343 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012344 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012345 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012346 return V;
12347 }
12348
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012349 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000012350 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12351 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000012352 // Everything but the extracted element is replaced with the RHS.
12353 for (unsigned i = 0; i != NumElts; ++i) {
12354 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000012355 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000012356 }
12357 return V;
12358 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012359
12360 // If this insertelement is a chain that comes from exactly these two
12361 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000012362 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12363 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012364 return EI->getOperand(0);
12365
Chris Lattnerefb47352006-04-15 01:39:45 +000012366 }
12367 }
12368 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012369 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000012370
12371 // Otherwise, can't do anything fancy. Return an identity vector.
12372 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000012373 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000012374 return V;
12375}
12376
12377Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12378 Value *VecOp = IE.getOperand(0);
12379 Value *ScalarOp = IE.getOperand(1);
12380 Value *IdxOp = IE.getOperand(2);
12381
Chris Lattner599ded12007-04-09 01:11:16 +000012382 // Inserting an undef or into an undefined place, remove this.
12383 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12384 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000012385
Chris Lattnerefb47352006-04-15 01:39:45 +000012386 // If the inserted element was extracted from some other vector, and if the
12387 // indexes are constant, try to turn this into a shufflevector operation.
12388 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12389 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12390 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000012391 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000012392 unsigned ExtractedIdx =
12393 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000012394 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000012395
12396 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12397 return ReplaceInstUsesWith(IE, VecOp);
12398
12399 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012400 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000012401
12402 // If we are extracting a value from a vector, then inserting it right
12403 // back into the same place, just use the input vector.
12404 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12405 return ReplaceInstUsesWith(IE, VecOp);
12406
12407 // We could theoretically do this for ANY input. However, doing so could
12408 // turn chains of insertelement instructions into a chain of shufflevector
12409 // instructions, and right now we do not merge shufflevectors. As such,
12410 // only do this in a situation where it is clear that there is benefit.
12411 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12412 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12413 // the values of VecOp, except then one read from EIOp0.
12414 // Build a new shuffle mask.
12415 std::vector<Constant*> Mask;
12416 if (isa<UndefValue>(VecOp))
Owen Anderson1d0be152009-08-13 21:58:54 +000012417 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000012418 else {
12419 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson1d0be152009-08-13 21:58:54 +000012420 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
Chris Lattnerefb47352006-04-15 01:39:45 +000012421 NumVectorElts));
12422 }
Owen Andersond672ecb2009-07-03 00:17:18 +000012423 Mask[InsertedIdx] =
Owen Anderson1d0be152009-08-13 21:58:54 +000012424 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000012425 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012426 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012427 }
12428
12429 // If this insertelement isn't used by some other insertelement, turn it
12430 // (and any insertelements it points to), into one big shuffle.
12431 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12432 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012433 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000012434 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012435 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000012436 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000012437 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000012438 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000012439 }
12440 }
12441 }
12442
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000012443 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12444 APInt UndefElts(VWidth, 0);
12445 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12446 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12447 return &IE;
12448
Chris Lattnerefb47352006-04-15 01:39:45 +000012449 return 0;
12450}
12451
12452
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012453Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12454 Value *LHS = SVI.getOperand(0);
12455 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000012456 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012457
12458 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000012459
Chris Lattner867b99f2006-10-05 06:55:50 +000012460 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000012461 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012462 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000012463
Dan Gohman488fbfc2008-09-09 18:11:14 +000012464 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000012465
12466 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12467 return 0;
12468
Evan Cheng388df622009-02-03 10:05:09 +000012469 APInt UndefElts(VWidth, 0);
12470 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12471 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000012472 LHS = SVI.getOperand(0);
12473 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000012474 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000012475 }
Chris Lattnerefb47352006-04-15 01:39:45 +000012476
Chris Lattner863bcff2006-05-25 23:48:38 +000012477 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12478 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12479 if (LHS == RHS || isa<UndefValue>(LHS)) {
12480 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012481 // shuffle(undef,undef,mask) -> undef.
12482 return ReplaceInstUsesWith(SVI, LHS);
12483 }
12484
Chris Lattner863bcff2006-05-25 23:48:38 +000012485 // Remap any references to RHS to use LHS.
12486 std::vector<Constant*> Elts;
12487 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012488 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000012489 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012490 else {
12491 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000012492 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000012493 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000012494 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000012495 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000012496 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000012497 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000012498 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000012499 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012500 }
Chris Lattner863bcff2006-05-25 23:48:38 +000012501 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012502 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000012503 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012504 LHS = SVI.getOperand(0);
12505 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012506 MadeChange = true;
12507 }
12508
Chris Lattner7b2e27922006-05-26 00:29:06 +000012509 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000012510 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000012511
Chris Lattner863bcff2006-05-25 23:48:38 +000012512 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12513 if (Mask[i] >= e*2) continue; // Ignore undef values.
12514 // Is this an identity shuffle of the LHS value?
12515 isLHSID &= (Mask[i] == i);
12516
12517 // Is this an identity shuffle of the RHS value?
12518 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000012519 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012520
Chris Lattner863bcff2006-05-25 23:48:38 +000012521 // Eliminate identity shuffles.
12522 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12523 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012524
Chris Lattner7b2e27922006-05-26 00:29:06 +000012525 // If the LHS is a shufflevector itself, see if we can combine it with this
12526 // one without producing an unusual shuffle. Here we are really conservative:
12527 // we are absolutely afraid of producing a shuffle mask not in the input
12528 // program, because the code gen may not be smart enough to turn a merged
12529 // shuffle into two specific shuffles: it may produce worse code. As such,
12530 // we only merge two shuffles if the result is one of the two input shuffle
12531 // masks. In this case, merging the shuffles just removes one instruction,
12532 // which we know is safe. This is good for things like turning:
12533 // (splat(splat)) -> splat.
12534 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12535 if (isa<UndefValue>(RHS)) {
12536 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12537
12538 std::vector<unsigned> NewMask;
12539 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12540 if (Mask[i] >= 2*e)
12541 NewMask.push_back(2*e);
12542 else
12543 NewMask.push_back(LHSMask[Mask[i]]);
12544
12545 // If the result mask is equal to the src shuffle or this shuffle mask, do
12546 // the replacement.
12547 if (NewMask == LHSMask || NewMask == Mask) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012548 unsigned LHSInNElts =
12549 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Chris Lattner7b2e27922006-05-26 00:29:06 +000012550 std::vector<Constant*> Elts;
12551 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
Mon P Wangfe6d2cd2009-01-26 04:39:00 +000012552 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson1d0be152009-08-13 21:58:54 +000012553 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012554 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +000012555 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012556 }
12557 }
12558 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12559 LHSSVI->getOperand(1),
Owen Andersonaf7ec972009-07-28 21:19:26 +000012560 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000012561 }
12562 }
12563 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000012564
Chris Lattnera844fc4c2006-04-10 22:45:52 +000012565 return MadeChange ? &SVI : 0;
12566}
12567
12568
Robert Bocchino1d7456d2006-01-13 22:48:06 +000012569
Chris Lattnerea1c4542004-12-08 23:43:58 +000012570
12571/// TryToSinkInstruction - Try to move the specified instruction from its
12572/// current block into the beginning of DestBlock, which can only happen if it's
12573/// safe to move the instruction past all of the instructions between it and the
12574/// end of its block.
12575static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12576 assert(I->hasOneUse() && "Invariants didn't hold!");
12577
Chris Lattner108e9022005-10-27 17:13:11 +000012578 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000012579 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000012580 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000012581
Chris Lattnerea1c4542004-12-08 23:43:58 +000012582 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000012583 if (isa<AllocaInst>(I) && I->getParent() ==
12584 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000012585 return false;
12586
Chris Lattner96a52a62004-12-09 07:14:34 +000012587 // We can only sink load instructions if there is nothing between the load and
12588 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000012589 if (I->mayReadFromMemory()) {
12590 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000012591 Scan != E; ++Scan)
12592 if (Scan->mayWriteToMemory())
12593 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000012594 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000012595
Dan Gohman02dea8b2008-05-23 21:05:58 +000012596 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000012597
Dale Johannesenbd8e6502009-03-03 01:09:07 +000012598 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000012599 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000012600 ++NumSunkInst;
12601 return true;
12602}
12603
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012604
12605/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12606/// all reachable code to the worklist.
12607///
12608/// This has a couple of tricks to make the code faster and more powerful. In
12609/// particular, we constant fold and DCE instructions as we go, to avoid adding
12610/// them to the worklist (this significantly speeds up instcombine on code where
12611/// many instructions are dead or constant). Additionally, if we find a branch
12612/// whose condition is a known constant, we only visit the reachable successors.
12613///
12614static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000012615 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000012616 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012617 const TargetData *TD) {
Chris Lattner2806dff2008-08-15 04:03:01 +000012618 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012619 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012620
Chris Lattner2c7718a2007-03-23 19:17:18 +000012621 while (!Worklist.empty()) {
12622 BB = Worklist.back();
12623 Worklist.pop_back();
12624
12625 // We have now visited this block! If we've already been here, ignore it.
12626 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012627
12628 DbgInfoIntrinsic *DBI_Prev = NULL;
Chris Lattner2c7718a2007-03-23 19:17:18 +000012629 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12630 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012631
Chris Lattner2c7718a2007-03-23 19:17:18 +000012632 // DCE instruction if trivially dead.
12633 if (isInstructionTriviallyDead(Inst)) {
12634 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000012635 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012636 Inst->eraseFromParent();
12637 continue;
12638 }
12639
12640 // ConstantProp instruction if trivially constant.
Owen Anderson50895512009-07-06 18:42:36 +000012641 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012642 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12643 << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000012644 Inst->replaceAllUsesWith(C);
12645 ++NumConstProp;
12646 Inst->eraseFromParent();
12647 continue;
12648 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000012649
Devang Patel7fe1dec2008-11-19 18:56:50 +000012650 // If there are two consecutive llvm.dbg.stoppoint calls then
12651 // it is likely that the optimizer deleted code in between these
12652 // two intrinsics.
12653 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12654 if (DBI_Next) {
12655 if (DBI_Prev
12656 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12657 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012658 IC.Worklist.Remove(DBI_Prev);
Devang Patel7fe1dec2008-11-19 18:56:50 +000012659 DBI_Prev->eraseFromParent();
12660 }
12661 DBI_Prev = DBI_Next;
Zhou Sheng8313ef42009-02-23 10:14:11 +000012662 } else {
12663 DBI_Prev = 0;
Devang Patel7fe1dec2008-11-19 18:56:50 +000012664 }
12665
Chris Lattner7a1e9242009-08-30 06:13:40 +000012666 IC.Worklist.Add(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012667 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000012668
12669 // Recursively visit successors. If this is a branch or switch on a
12670 // constant, only visit the reachable successor.
12671 TerminatorInst *TI = BB->getTerminator();
12672 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12673 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12674 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000012675 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012676 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012677 continue;
12678 }
12679 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12680 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12681 // See if this is an explicit destination.
12682 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12683 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000012684 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000012685 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000012686 continue;
12687 }
12688
12689 // Otherwise it is the default destination.
12690 Worklist.push_back(SI->getSuccessor(0));
12691 continue;
12692 }
12693 }
12694
12695 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12696 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012697 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012698}
12699
Chris Lattnerec9c3582007-03-03 02:04:50 +000012700bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012701 bool Changed = false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012702 TD = getAnalysisIfAvailable<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000012703
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000012704 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12705 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000012706
Chris Lattnerb3d59702005-07-07 20:40:38 +000012707 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000012708 // Do a depth-first traversal of the function, populate the worklist with
12709 // the reachable instructions. Ignore blocks that are not reachable. Keep
12710 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000012711 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000012712 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000012713
Chris Lattnerb3d59702005-07-07 20:40:38 +000012714 // Do a quick scan over the function. If we find any blocks that are
12715 // unreachable, remove any instructions inside of them. This prevents
12716 // the instcombine code from having to deal with some bad special cases.
12717 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12718 if (!Visited.count(BB)) {
12719 Instruction *Term = BB->getTerminator();
12720 while (Term != BB->begin()) { // Remove instrs bottom-up
12721 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000012722
Chris Lattnerbdff5482009-08-23 04:37:46 +000012723 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000012724 // A debug intrinsic shouldn't force another iteration if we weren't
12725 // going to do one without it.
12726 if (!isa<DbgInfoIntrinsic>(I)) {
12727 ++NumDeadInst;
12728 Changed = true;
12729 }
Chris Lattnerb3d59702005-07-07 20:40:38 +000012730 if (!I->use_empty())
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012731 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000012732 I->eraseFromParent();
12733 }
12734 }
12735 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012736
Chris Lattner873ff012009-08-30 05:55:36 +000012737 while (!Worklist.isEmpty()) {
12738 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000012739 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000012740
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012741 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000012742 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012743 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000012744 EraseInstFromFunction(*I);
12745 ++NumDeadInst;
Chris Lattner1e19d602009-01-31 07:04:22 +000012746 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012747 continue;
12748 }
Chris Lattner62b14df2002-09-02 04:59:56 +000012749
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012750 // Instruction isn't dead, see if we can constant propagate it.
Owen Anderson50895512009-07-06 18:42:36 +000012751 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012752 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000012753
Chris Lattner8c8c66a2006-05-11 17:11:52 +000012754 // Add operands to the worklist.
Chris Lattnerc736d562002-12-05 22:41:53 +000012755 ReplaceInstUsesWith(*I, C);
Chris Lattner62b14df2002-09-02 04:59:56 +000012756 ++NumConstProp;
Chris Lattner7a1e9242009-08-30 06:13:40 +000012757 EraseInstFromFunction(*I);
Chris Lattner1e19d602009-01-31 07:04:22 +000012758 Changed = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000012759 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000012760 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000012761
Eli Friedmanfd2934f2009-07-15 22:13:34 +000012762 if (TD) {
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012763 // See if we can constant fold its operands.
Chris Lattner1e19d602009-01-31 07:04:22 +000012764 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12765 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Anderson50895512009-07-06 18:42:36 +000012766 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12767 F.getContext(), TD))
Chris Lattner1e19d602009-01-31 07:04:22 +000012768 if (NewC != CE) {
12769 i->set(NewC);
12770 Changed = true;
12771 }
Nick Lewycky3dfd7bf2008-05-25 20:56:15 +000012772 }
12773
Chris Lattnerea1c4542004-12-08 23:43:58 +000012774 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000012775 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000012776 BasicBlock *BB = I->getParent();
12777 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12778 if (UserParent != BB) {
12779 bool UserIsSuccessor = false;
12780 // See if the user is one of our successors.
12781 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12782 if (*SI == UserParent) {
12783 UserIsSuccessor = true;
12784 break;
12785 }
12786
12787 // If the user is one of our immediate successors, and if that successor
12788 // only has us as a predecessors (we'd have to split the critical edge
12789 // otherwise), we can keep going.
12790 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12791 next(pred_begin(UserParent)) == pred_end(UserParent))
12792 // Okay, the CFG is simple enough, try to sink this instruction.
12793 Changed |= TryToSinkInstruction(I, UserParent);
12794 }
12795 }
12796
Chris Lattner74381062009-08-30 07:44:24 +000012797 // Now that we have an instruction, try combining it to simplify it.
12798 Builder->SetInsertPoint(I->getParent(), I);
12799
Reid Spencera9b81012007-03-26 17:44:01 +000012800#ifndef NDEBUG
12801 std::string OrigI;
12802#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000012803 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Chris Lattner74381062009-08-30 07:44:24 +000012804
Chris Lattner90ac28c2002-08-02 19:29:35 +000012805 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000012806 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012807 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012808 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000012809 DEBUG(errs() << "IC: Old = " << *I << '\n'
12810 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000012811
Chris Lattnerf523d062004-06-09 05:08:07 +000012812 // Everything uses the new instruction now.
12813 I->replaceAllUsesWith(Result);
12814
12815 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000012816 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012817 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012818
Chris Lattner6934a042007-02-11 01:23:03 +000012819 // Move the name to the new instruction first.
12820 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012821
12822 // Insert the new instruction into the basic block...
12823 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000012824 BasicBlock::iterator InsertPos = I;
12825
12826 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12827 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12828 ++InsertPos;
12829
12830 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000012831
Chris Lattner7a1e9242009-08-30 06:13:40 +000012832 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000012833 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000012834#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000012835 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12836 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000012837#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000012838
Chris Lattner90ac28c2002-08-02 19:29:35 +000012839 // If the instruction was modified, it's possible that it is now dead.
12840 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000012841 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012842 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000012843 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000012844 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000012845 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000012846 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000012847 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012848 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000012849 }
12850 }
12851
Chris Lattner873ff012009-08-30 05:55:36 +000012852 Worklist.Zap();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012853 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012854}
12855
Chris Lattnerec9c3582007-03-03 02:04:50 +000012856
12857bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000012858 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000012859 Context = &F.getContext();
Chris Lattnerf964f322007-03-04 04:27:24 +000012860
Chris Lattner74381062009-08-30 07:44:24 +000012861
12862 /// Builder - This is an IRBuilder that automatically inserts new
12863 /// instructions into the worklist when they are created.
12864 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12865 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12866 InstCombineIRInserter(Worklist));
12867 Builder = &TheBuilder;
12868
Chris Lattnerec9c3582007-03-03 02:04:50 +000012869 bool EverMadeChange = false;
12870
12871 // Iterate while there is work to do.
12872 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000012873 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000012874 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000012875
12876 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000012877 return EverMadeChange;
12878}
12879
Brian Gaeke96d4bf72004-07-27 17:43:21 +000012880FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000012881 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000012882}